【正文】
Fixing Memory Problems This chapter is about finding bugs in C/C++ programs with the help of a memory debugger. A memory debugger is a runtime tool designed to trace and detect bugs in C/C++ memory management and access. It does not replace a general debugger. In the following sections, we will describe the memory access bugs that typically occur in C/C++ programs, introduce memory debuggers, and show with two examples how these tools find bugs. We will then show how to run memory and source code debuggers together, how to deal with unwanted error messages by writing a suppression file, and what restrictions need to be considered. Memory Management in C/C++ – Powerful but Dangerous The C/C++ language is able to manage memory resources, and can access memory directly through pointers. Efficient memory handling and “programming close to the hardware” are reasons why C/C++ replaced assembly language in the implementation of large software projects such as operating systems, where performance and low overhead play a major role. The allocation of dynamic memory (also known as heap memory) in C/C++ is under the control of the programmer. New memory is allocated with functions such as malloc() and various forms of the operator new. Unused memory is returned with free() or delete. The memory handling in C/C++ gives a large degree of freedom, control, and performance, but es at a high price: the memory access is a frequent source of bugs. The most frequent sources of memory access bugs are memory leaks, incorrect use of memory management, buffer overruns, and reading uninitialized memory. 33 34 4 Fixing Memory Problems Memory Leaks Memory leaks are data structures that are allocated at runtime, but not deallocated once they are no longer needed in the program. If the leaks are frequent or large, eventually all available main memory in your puter will be consumed. The program will first slow down, as the puter starts swapping pages to virtual memory, and then fail with an outofmemory error. Finding leaks with a general debugger is difficult because there is no obvious faulty statement. The bug is that a statement is missing or not called. Incorrect Use of Memory Management A whole class of bugs is associated with incorrect calls to memory manageme nt: freeing a block of memory more than once, accessing memory after freeing it, or freeing a block that was never allocated. Also belonging to this class is using