Memory Management¶
Memory regions¶
When a program written with C++ is executed, a section of physical memory is allocated to the program. The program will then partition the memory into regions.
- Code Memory Region¶
The memory region to store code binary.
- Static Memory Region¶
The memory region to store global and static variables.
- Stack Memory Region¶
The memory region to store formal parameters and local variables allocated during function calls. Also known as automatic memory region.
- Heap Memory Region¶
The memory region to store data allocated using the
new
operator. Also known as dynamic memory region.
Stack and Function Calls¶
Stack is an ADT in which elements are added and removed in a first in last out order (FILO). It aligned well with the requirement to store data required in function calls. The memory allocated for function calls in C++ is thus named the stack memory region.
In C++, every function call requires the data storage of all formal parameters
and local variables. They are packed into a Stack Frame
and pushed into
the stack when the function is called. The Stack Frame
is popped and
removed from the stack when the function returns.
Dynamic Memory Allocation¶
Data stored in heap
new
creates the data structure in heap memory and returns a pointerint *intPtr = new int; // single variable int *array = new int[10]; // array MyClass *myObjPtr = new MyClass(); // object
delete
destruct the data structure the pointer is pointing to and release the memory in heapalways call delete on a pointer (dynamic array is also a pointer)
add [] if the pointer is pointing to a list of memory blocks (array)
delete intPtr; delete [] array1; delete myObjPtr;
The allocated data in heap are known as dynamic data
Memory Problems¶
Memory leak¶
Only for data stored in the heap region (dynamic data)
Dynamic data allocated (new) but not released (delete)
Likely to be overlooked in function and class definitions when the flow of control is not obvious
Other Problems¶
Stack overflow because of endless function calls, e.g. recursion
Out-of-boundary array index
Oversized C string operations
Uninitialized pointer access
Deleting the same pointer multiple times
Memory Problem Checking Tool¶
Note
Optional reading material. Beneficial to projects depending on working style.
The command line tool valgrind
, read instruction here
Dynamic Data and Functions¶
Refer to the Return an Array section for details on how dynamic data allows returning an array from a function.
You can return dynamic data that are not array also.