To use free()
, it is important to only free items which have come from malloc()
or calloc()
(or reprocessed by realloc()
). Those (along with free()) manage the heap.
int *p = malloc (5620); /* allocate 5620 bytes */
/* do something with memory at p */
....
free (p);
While other pointers match the data type of free() that is not sufficient. To free a pointer not from malloc() is practically guaranteed to cause serious trouble: immediately crashing the program, introducing a subtle bug which causes weird results later, or clobbers something unrelated.
The heap is one or more areas of the process's memory which provides space to dynamically allocate many types and instances of objects. Those areas do not have to be associated to a particular program variable; linked lists, trees, graphs, and other data structures are naturally held in the heap.