Debugging Dynamic Memory Usage Errors Using HP WDB (5900-1474; WDB 6.2; January 2011)

Step by Step Approach for Detecting Leaks
This section provides the guidelines and a sample test case to enable you detect memory
leaks by going through a step by step procedure.
Steps to Detect Point of Memory Leak
To detect the point of memory leak, ensure that you go through following steps:
1. Enable memory leak detection for the application run and collect the leak report in
batch mode. To enable leak detection, use check_leaks=on in the rtcconfig
file.
2. The batch mode run reports memory leaks. From this report, pick up the leaks one
by one and detect the point of leak following the instructions below. Run the
application under gdb with the -leaks command.
3. Detect the location of memory leak using the steps mentioned below.
a. Insert a breakpoint at the function that allocates the memory. Step into the calling
function using the finish command and collect leak information with the info
leaks command after the execution reaches the calling function.
NOTE: If the address of the allocated memory location is in a register or if the
address is in RSE contents, then the leak information is not shown and henceforth
means that some data in the program still points to the allocated memory.
b. Continue the previous step and step into the next calling function in the stack
trace and collect leak information with the info leaks command after the
execution reaches the next calling function. If a leak information is displayed,
then you can infer that the pointer to the allocated memory is lost before getting
into the function or in the function.
c. Find the statement causing the loss of this pointer to the allocated memory in
caller of the current function or in the current function.
Sample Test Case to Detect Point of Memory Leak
The “Steps to Detect Point of Memory Leak” (page 89) are represented through a sample
test case. The sample test case is provided as shown below:
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4
5 /* Allocate memory and return it to the caller */
6 void *allocateMemory(size_t n)
7 {
8 void *memBlock = NULL;
9 printf("Allocating memory of size %d\n", n);
10
11 memBlock = malloc(n);
12 if (!memBlock)
13 {
Step by Step Approach for Detecting Leaks 89