5 ms·
struct foo { int a; char star b; } struct foo star p = malloc(sizeof (struct foo) + 100); p->b[50] = 'x';
by sys_64738 6y ago
struct foo {
int a;
char star b;
}
struct foo star p = malloc(sizeof (struct foo) + 100);
p->b[50] = 'x';
- enriquto 6y agoYou can quote your code (by preceeding it with four spaces) so that your stars become visible: struct foo { int a; char *b; } struct foo *p = malloc(sizeof (struct foo) + 100); p->b[50] = 'x'; ... free(p);
- wruza 6y agoIsn't it two spaces at least? Test Upd: yes it is.
- saagarjha 6y agoI think you have an initialized read in your code…
- saagarjha 6y ago* uninitialized :/
- huhtenberg 6y agoThis 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.