Monday, February 01, 2010

Garbage in C

p = malloc(...);
q = malloc(...);
/* free (p); */

p = q;


p points to one memory block and q points to another.

After q is assigned to p, both point the the second memory block. There are no pointers to the first block. This memory block cannot be accessible to program, it is called ‘garbage’. A program that leaves garbage behind has memory leak. C doesn’t have garbage collector.

You can use ‘free(p)’ to release the memory block that p points to.

After you released the memory block, if you attempt to access or modify this deallocated memory block, it causes undefined behavior.

No comments:

Post a Comment