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?
The members are part of the structure. Freeing the structure deallocates all of its members.
However, in your example, the members are just pointers. You're copying a pointer into the structure (node->data1 = ...
), then out of the structure (... = node->data1
), then freeing the structure. None of this affects the memory that the pointer is pointing to.
In your example the actual strings are stored in static memory (they're string literals). That means they're never destroyed; they live as long as the program is running. That's why it's perfectly safe to print them. Your code is fine.
Finally, accessing freed memory has undefined behavior (meaning anything can happen, including a program crash or appearing to work correctly). If you want to access members of a structure that has been freed, just do that:
struct elem *p = malloc(sizeof *p);
free(p);
p->data1 = "boom!"; // Undefined behavior!
However, that would be a bug, so ... don't, please.