Why freed struct in C still has data?

When I run this code:

#include <stdio.h>

typedef struct _Food
{
    char          name [128];
} Food;

int
main (int argc, char **argv)
{
    Food  *food;

food = (Food*) malloc (sizeof (Food));
snprintf (food->name, 128, "%s", "Corn");

free (food);

printf ("%d\n", sizeof *food);
printf ("%s\n", food->name);
}

I still get

128
Corn

although I have freed food. Why is this? Is memory really freed?


Solution 1:

When you free 'food', you are saying you are done with it. However, the pointer food still points to the same address, and that data is still there (it would be too much overhead to have to zero out every bit of memory that's freed when not necessary)

Basically it's because it's such a small example that this works. If any other malloc calls were in between the free and the print statements, there's a chance that you wouldn't be seeing this, and would most likely crash in some awful way. You shouldn't rely on this behavior.

Solution 2:

There is nothing like free food :) When you "free" something, it means that the same space is again ready to be used by something else. It does NOT mean filling it up by garbage. Secondly, the pointer value has not changed -- if you are seriously coding you should set a pointer to NULL once you have freed it so that potential junk accesses like this do not happen.

Solution 3:

Freeing memory doesn't necessarily overwrite the contents of it.