Debugging Dynamic Memory Usage Errors Using HP WDB

Heap corruption occurs when a program tries to free memory that is not allocated to the program.
Such instances include freeing un-initialized pointers where the pointer addresses memory
outside the allocated memory. (Example 17 (page 68) illustrates how WDB detects such errors.)
Accessing freed memory
Accessing freed memory results in heap corruption. The scramble feature is a minimal aid to
detect such errors. See “Scrambling a Heap Block” (page 54) for more information.
Memory Leaks
A memory leak occurs when an application fails to free allocated memory. As a result, the kernel
frees the memory that is allocated by a process only when the process terminates. If the program
leaks memory on a continual basis, the virtual memory requirement for the process continues
to increase and this can result in serious consequences for long-running applications and memory
intensive applications.
Memory leaks can also cause fragmentation of the heap. This slows down the allocation,
de-allocation, and access of memory blocks and can eventually cause the application to fail with
out-of-memory errors.
When to Suspect a Memory Leak?
You must suspect a memory leak in an application if the system runs out of swap space, runs
slower, or both. Memory leaks in an application increase the memory consumption in an
application. When the memory consumed by the application exceeds the resource limits set by
the kernel, the application fails with out-of-memory errors.
WDB enables you to detect out-of-memory conditions through runtime memory checking. It
also enables you to simulate out-of-memory conditions in an application to understand application
behavior under such conditions.
For information on how you can use WDB to simulate and detect out-of-memory conditions in
an application, see “Error Injection (page 30)
Types of Memory Leaks
Following are the types of memory leaks:
Physical Leaks
A physical leak is a definite memory leak that occurs when an application loses all handles,
or all pointers to the allocated memory. If a valid pointer to a memory block is absent, the
elusive block of memory cannot be accessed or freed.
The handles to a memory block are typically lost under the following conditions:
When an application overwrites a pointer that addresses a block of memory with another
address or data
— When a pointer variable goes out of scope
— When you free a structure or an array that has pointers which are not freed
When all handles to a block of memory are lost, it causes the block to be leaked. Example 19
(page 70), Example 20 (page 71), and Example 21 (page 72) illustrate how WDB detects
memory leaks.
Logical Leaks
A logical leak occurs when an application fails to optimally utilize the allocated memory.
In this case the allocated block of memory can still be accessed through a pointer variable
in the application.
14