Expert C Programming

(Jeff_L) #1

Avoiding Memory Leaks


Whenever you write malloc, write a corresponding free statement.


If you don't know where to put the "free" that corresponds to your "malloc", then you've
probably created a memory leak!


One simple way to avoid this is to use alloca() for your dynamic needs when possible.
The alloca() routine allocates memory on the stack; when you leave the function in
which you called it, the memory is automatically freed.


Clearly, this can't be used for structures that need a longer lifetime than the function
invocation in which they are created; but for stuff that can live within this constraint,
dynamic memory allocation on the stack is a low-overhead choice. Some people deprecate
the use of alloca because it is not a portable construct. alloca() is hard to implement
efficiently on processors that do not support stacks in hardware.


We use the term "memory leak" because a scarce resource is draining away in a process. The main
user-visible symptom of a memory leak is that the guilty process slows down. This happens because
larger processes are more likely to have to be swapped out to give other processes a chance to run.
Larger processes also take a longer time to swap in and out. Even though (by definition) the leaked
memory itself isn't referenced, it's likely to be on a page with something that is, thus enlarging the
working set and slowing performance. An additional point to note is that a leak will usually be larger
than the size of the forgotten data structure, because malloc() usually rounds up a storage request to
the next larger power-of-two. In the limiting case, a process with a memory leak can slow the whole
machine down, not just the user running the offending program. A process has a theoretical size limit
that varies from OS to OS. On current releases of SunOS, a process address space can be up to 4
Gbytes; in practice, swap space would be exhausted long before a process leaked enough memory to
grow that big. If you're reading this book five years after it was written, say around the turn of the
millenium, you'll probably get a good laugh over this by then long-obsolete restriction.


How to Check for a Memory Leak


Looking for a memory leak is a two-step process. First you use the swap command to see how much
swap space is available:


/usr/sbin/swap -s


total: 17228k bytes allocated + 5396k reserved = 22624k used,


29548k


available

Free download pdf