Expert C Programming

(Jeff_L) #1

Everything in the heap is anonymous—you cannot access it directly by name, only indirectly through
a pointer. The malloc (and friends: calloc, realloc, etc.) library call is the only way to obtain storage
from the heap. The function c alloc is like malloc, but clears the memory to zero before giving you
the pointer. Don't think that the "c " in c alloc() has anything to do with C programming—it means


"allocate zeroized memory". The function realloc() changes the size of a block of memory pointed
to, either growing or shrinking it, often by copying the contents somewhere else and giving you back a
pointer to the new location. This is useful when growing the size of tables dynamically—more about
this in Chapter 10.


Figure 7-5. Where the Heap Lives

Heap memory does not have to be returned in the same order in which it was acquired (it doesn't have
to be returned at all), so unordered malloc/free's eventually cause heap fragmentation. The heap must
keep track of different regions, and whether they are in use or available to malloc. One scheme is to
have a linked list of available blocks (the "free store"), and each block handed to malloc is preceded
by a size count that goes with it. Some people use the term arena to describe the set of blocks
managed by a memory allocator (in SunOS, the area between the end of the data segment and the
current position of the break).

Free download pdf