For an array T arr[10]
, sizeof arr
returns the number of bytes occupied by the array (ie. sizeof(T) * 10
in this case.) However, swprintf
expects the number of wchar_t
in the destination buffer as its second argument.
The swprintf() function shall place output followed by the null wide character in consecutive wide characters starting at *ws; no more than n wide characters shall be written, including a terminating null wide character, which is always added (unless n is zero).
The below test code shows how the canary values are destroyed when you simply use sizeof a
and the source wchar_t
string is longer than the destination wchar_t
buffer.
#include <wchar.h>
#include <stdio.h>
#define ARRLEN(a) (sizeof(a) / sizeof(a[0]))
int main() {
struct S {
int i;
wchar_t a[4];
int j, k, l;
};
struct S x = {}, y = {};
wchar_t b[] = L"984567";
int rcx, rcy;
printf("Start\n");
printf("%ld %ld\n", sizeof(x.a), sizeof(x.a[0]));
rcx = swprintf(x.a, ARRLEN(x.a), L"%ls", b);
rcy = swprintf(y.a, sizeof(y.a), L"%ls", b);
printf("%#x %ls %#x %#x %#x %d\n", x.i, x.a, x.j, x.k, x.l, rcx);
printf("%#x %ls %#x %#x %#x %d\n", y.i, y.a, y.j, y.k, y.l, rcy);
printf("%ls\n", b);
printf("end\n");
return 0;
}