Memory Management
Memory Management
MANAGEMENT
Allocating memory
There are two ways that memory gets allocated for data storage:
• Compile Time (or static) Allocation
– Memory for named variables is allocated by the compiler
– Exact size and type of storage must be known at compile time
– For standard array declarations, this is why the size has to be constant
• Dynamic Memory Allocation
– Memory allocated "on the fly" during run time
– dynamically allocated space usually placed in a program segment known as the heap or the
free store
– Exact amount of space or number of items does not have to be known by the compiler in
advance.
– For dynamic memory allocation, pointers are crucial
Memory allocation
• Memory in your C++ program is divided into two parts −
• The stack − All variables declared inside the function will take up
memory from the stack.
• The heap − This is unused memory of the program and can be
used to allocate the memory dynamically when program runs.
• Many times, you are not aware in advance how much memory
you will need to store particular information in a defined
variable and the size of required memory can be determined at
run time.
Dynamic Memory allocation
• You can allocate memory at run time within the heap for the
variable of a given type using a special operator in C++ which
returns the address of the space allocated. This operator is
called new operator.
delete pointer_variable;
If creating an array dynamically, use the same form, but put brackets with a size after the type:
new int[40]; // dynamically allocates an array of 40 ints
new double[size]; // dynamically allocates an array of size doubles
// note that the size can be a variable
These statements above are not very useful by themselves, because the allocated spaces have no names!
BUT, the new operator returns the starting address of the allocated space, and this address can be stored
in a pointer:
int * p; // declare a pointer p
p = new int; // dynamically allocate an int and load address into p
• A memory leak can diminish the performance of the computer by reducing the
amount of available memory. Eventually, in the worst case, too much of the
available memory may become allocated and all or part of the system or device
stops working correctly, the application fails
An example of memory leak
• When a button is pressed: Get some memory, which will be
used to remember the floor number
• Put the floor number into the memory
• Are we already on the target floor?
• If so, we have nothing to do: finished Otherwise: Wait until the
lift is idle Go to the required floor
• Release the memory we used to remember the floor number
Allocation failure
• When an attempt is made to allocate to the heap but
insufficient memory is available, an allocation failure is
triggered. The output produced depends on the area of the
heap in which the allocation failure occurred.