Dynamic Memory Allocation
Download
Report
Transcript Dynamic Memory Allocation
Dynamic Storage Allocation
CS362
Dynamic Storage Allocation
Needed understanding of the amount of data to be stored.
For example: amount of data required to size an array.
If not known, best guess, not the best situation.
As program executes “dynamic (runtime) memory” is
allocated (otherwise known as the heap)
Static Memory – allocated during the compilation of the program
Dynamic Memory – allocated during the execution of the program
We can access the dynamic memory via pointers
Dynamic Memory Allocation
To create dynamic variables we use the “new” operator
“new” allocates either:
one storage cell and returns a pointer to the cell
a series of contiguous storage cells (an array) and returns a pointer
to the first cell (dynamic array)
For example:
int *ptr, *iptr;
ptr = new int;
// pointer to a single integer in dynamic memory
or
iptr = new int[size]; // pointer to a dynamic array of integer, this is
// an anonymous array and can only be accessed
// via pointers
Dynamic Memory Allocation
Programs often use memory on a temporary basis.
Memory no longer required should be de-allocated.
De-allocation returns memory to the heap.
Which means it can be re-used.
Memory is de-allocated using the “delete” operator
“delete” returns the space allocated by “new”
For example:
delete ptr;
or
delete [ ] iptr;
// deallocated single memory location
// deallocates the entire array
Pointers still exist, but do not point to anything.
Dynamic Memory Allocation
After de-allocating memory, the pointer still points at the
same memory location, but it is now inaccessible
A pointer without a valid value is a “dangling pointer”
An attempt to access the memory may crash the program
Eliminate this issue by setting the pointer variable to NULL