Expert C Programming

(Jeff_L) #1

Malloced memory is always aligned appropriately for the largest size of atomic access on a machine,
and a malloc request may be rounded up in size to some convenient power of two. Freed memory goes
back into the heap for reuse, but there is no (convenient) way to remove it from your process and give
it back to the operating system.


The end of the heap is marked by a pointer known as the "break". [2] When the heap manager needs
more memory, it can push the break further away using the system calls brk and sbrk. You typically
don't call brk yourself explicitly, but if you malloc enough memory, brk will eventually be called for
you. The calls that manage memory are:


[2] Your programs will "break" if they reference past the break...


malloc and free— get memory from heap and give it back to heap


brk and sbrk— adjust the size of the data segment to an absolute value/by an increment


One caution: your program may not call both malloc() and brk(). If you use malloc, malloc
expects to have sole control over when brk and sbrk are called. Since sbrk provides the only way for a
process to return data segment memory to the kernel, if you use malloc you are effectively prevented
from ever shrinking the program data segment in size. To obtain memory that can later be returned to
the kernel, use the mmap system call to map the /dev/zero file. To return this memory, use munmap.


Memory Leaks

Some programs don't need to manage their dynamic memory use; they simply allocate what they need,
and never worry about freeing it. This class includes compilers and other programs that run for a fixed
or bounded period of time and then terminate. When such a program finishes, it automatically
relinquishes all its memory, and there is little need to spend time giving up each byte as soon as it will
no longer be used.


Other programs are more long-lived. Certain utilities such as calendar manager, mailtool, and the
operating system itself have to run for days or weeks at a time, and manage the allocation and freeing
of dynamic memory. Since C does not usually have garbage collection (automatic identification and
deallocation of memory blocks no longer in use) these C programs have to be very careful in their use
of malloc() and free(). There are two common types of heap problems:



  • freeing or overwriting something that is still in use (this is a "memory corruption")

  • not freeing something that is no longer in use (this is a "memory leak")


These are among the hardest problems to debug. If the programmer does not free each malloced block
when it is no longer needed, the process will acquire more and more memory without releasing the
portions no longer in use.


Handy Heuristic

Free download pdf