4 ms·
This will crash, because 'b' will be uninitialized and pointing at some random memory spot. A conventional and working form of the same is struct foo { i
by huhtenberg 6y ago
This will crash, because 'b' will be uninitialized and pointing at some random memory spot.
A conventional and working form of the same is
struct foo { int a; char b[1]; }
struct foo * p = malloc(sizeof (struct foo) + 99);
p->b[50] = 'x';
or, if the compiler allows it,
struct foo { int a; char b[0]; }
struct foo * p = malloc(sizeof (struct foo) + 100);
p->b[50] = 'x';
- sys_64738 6y agoRight yeah the middle with char b[1]. I was fighting with the asterisks being deleted to notice the mis-type. This method is used a lot in OS programming.
- Asooka 6y agoThis is undefined behaviour except when using msvc. For GCC and clang, you should use [] (empty square brackets) to denote a variable length array at the end of a struct. For msvc, [1] is used all over win32 and is explicitly supported for that purpose. Edit: it's UB because you're accessing past the end of an array with size given at compile time.
- kevin_thibedeau 6y ago[] syntax in the last struct member is a "flexible array member" not a VLA. The former hasn't been deprecated in C11.