pointers - Why does this C struct code work? -
i toying pointers structures , array of structures see how work. confounded why following piece of work compiles , produces right result:
#include <stdio.h> #include <stdlib.h> int main() { typedef struct { char *name; int count; } word; word *word_array; word_array = malloc(sizeof(word)); word_array[2048].name = "foo"; word_array[2048].count = 5; printf("%s %d\n", word_array[2048].name, word_array[2048].count);
this prints: foo 5
how memory malloc allocate word_array? what's going on? undefined behaviour happens compile , run?
how memory malloc allocate word_array?
sizeof(word)
bytes, told - enough memory hold 1 word
.
what's going on? undefined behaviour happens compile , run?
yes. note it's not surprising compiles (most undefined behaviour not cause compilation error, or warning).
since seem know undefined behaviour, know might crash, or might seem work, or in-between. maybe next tuesday program crash when try show ceo. maybe you'll upgrade compiler in 6 months , it'll start crashing consistently. if program writes files, then maybe it's corrupting files. , on.
Comments
Post a Comment