How does C free() work?

slee picture slee · Jan 16, 2011 · Viewed 20.7k times · Source

Possible Duplicate:
How malloc() and free() work

#include <stdio.h>
#include <stdlib.h>

int * alloc()
{
    int *p = (int *)calloc(5,4);
    printf("%d\n",p);
    return p;
}

int main()
{
 int *p = alloc();

 free(p);
 printf("%d\n",p);
 p[0] = 1;
 p[1] = 2;
 printf("%d %d\n",p[0],p[1]);
}

As to the code segment, I allocate 5 ints,first. And then I free the memory. When I printf p, why does p sill have a value same to the memory address allocated first? And I also can assign value to p[0] and p[1]. Does this mean free() do nothing? Once I allocate memory, I can use later though I have freed it.

Answer

Matthew Flaschen picture Matthew Flaschen · Jan 16, 2011

free releases the memory at that address. It doesn't change the p variable itself. However, doing anything with p after that point is undefined behavior. It may seem to work if you use it immediately after freeing, but it's still completely wrong, and could cause a crash or worse.

free is implementation-specific. However, on most implementations, it will write to book-keeping data in the heap to note that the memory is now available. For instance, it might mark a particular chunk as unused, or combine the chunk with an adjacent free one.

Note that using %d for a pointer is also undefined.