Friday, March 23, 2012

Memory Management Issues


The C/C++ language is able to manage memory resources, and can access memory directly through pointers.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 comes 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.

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 computer will be consumed. The program will first slow down, as the computer starts swapping pages to virtual memory, and then fail with an out-of-memory error.

Incorrect Use of Memory Management

A whole class of bugs is associated with incorrect calls to memory management: freeing a block of memory more than once, accessing memory after freeing it, or freeing a block that was never allocated.

Buffer Overruns

Buffer overruns are bugs where memory outside of the allocated boundaries is overwritten, or corrupted. Buffer overruns can occur for global variables, local variables on the stack, and dynamic variables that were allocated on the heap with memory management.

One nasty artifact of memory corruption is that the bug may not become visible at the statement where the memory is overwritten. Only later, another statement in the program will access this memory location. Because the memory location has an illegal value, the program can behave incorrectly in a number of ways: the program may compute a wrong result, or, if the illegal value is in a pointer, the program will try to access protected memory and crash. If a function pointer variable is overwritten, the program will do a jump and try to execute data as program code.

Uninitialized Memory Bugs

Reading uninitialized memory can occur because C/C++ allows creation of variables without an initial value.The memory allocation function malloc() and operator new also do not initialize or zero out the allocated memory blocks.

No comments:

Post a Comment