Expert C Programming

(Jeff_L) #1

to look at the manpage, and to see all the routines in the malloc family.


Make sure you link with the appropriate library. The SPARCWorks


debugger on Solaris 2.x has extensive features to help detect memory


leaks; these have supplanted the special malloc libraries on Solaris 1.x.


Software Dogma


The President and the Printtool—A Memory Leak Bug


The simplest form of memory leak is:


for (i=0; i<10; i++)


p = malloc(1024);


This is the Exxon Valdez of software; it leaks away everything you give it.


With each successive iteration, the previous address held in p is overwritten, and the Kbyte
block of memory that it points to "leaks away". Since nothing now points to it, there is no
way to access or free that memory. Most memory leaks aren't quite as blatant as overwriting
the only pointer to the block before it can be freed, so they are harder to identify and debug.


An interesting case occurred with the printtool software here at Sun. An internal test release
of the operating system was installed on the desktop system of Scott McNealy, the company
president. [1] The president soon noticed that over the course of a couple of days, his
workstation became slower and slower. Rebooting fixed it instantly. He reported the
problem, and nothing concentrates the mind like a bug report filed by the company
president.


We found that the problem was triggered by "printtool", a window interface around the print
command. "Printtool" is the kind of software much used by company presidents but not by
OS developers, which is why the problem had lain undiscovered. Killing printtool caused
the memory leak to stop, but ps -lu scott showed that printtool was only triggering the
leak, not growing in size itself. It was necessary to look at the system calls that printtool
used.


The design of printtool had it allocate a named pipe (a special type of file that allows two
unrelated processes to communicate) and use it to talk to the line printer process. A new
pipe was created every few seconds, then destroyed if printtool didn't have anything
interesting to tell the printer. The real memory leak bug was in the pipe creation system call.
When a pipe was created, kernel memory was allocated to hold the vnode data structure to
control it, but the code that kept a reference count for the structure was off by one.


As a result, when the true number of pipe users dropped to zero, the count stayed at 1, so the
kernel always thought the pipe was in use. Thus, the vnode struct was never freed as it
should have been when the pipe was closed. Every time a pipe was closed, a few hundred

Free download pdf