I'm pretty much new to C and i have a question about allocating memory. So I tried this code below that should free the structure elem1.
struct elem{
char *data1;
char *data2;
};
int main()
{
struct elem *elem1 = malloc(sizeof(struct elem));
elem1->data1 = "abc";
elem1->data2 = "def";
char *a = elem1->data1;
char *b = elem1->data2;
free(elem1);
printf("%s\n%s\n",a,b);
return 0;
}
The code compiles just fine and it gives back,
abc
def
I expected it to fail since free should also free the memory of its members. But why does it work? And what should I do if I want to access the members of the structure after I free the structure?