Showing posts from January, 2011

Memory Management in C++

A memory leak is a type of programming bug that occurs when a program allocates more memory than it frees. This way, an application can run out of memory and cause the system to crash. To prevent memory leaks, you need to know when they occur most frequently and be conscientious with your use of the "new" and "delete" C++ operators.

The C++ operator "new" allocates heap memory. The "delete" operator frees heap memory. For every "new," you should use a "delete" so that you free the same memory you allocated:

1.char* str = new char [30]; // Allocate 30 bytes to house a string.

delete [] str; // Clear those 30 bytes and make str point nowhere.

2.Reallocate memory only if you've deleted. In the code below, str acquires a new address with the second allocation. The first address is lost irretrievably, and so are the 30 bytes that it pointed to. Now they're impossible to free, and you have a memory leak:

char* str = new char […