Dynamic Memory Allocation
Variables explicitly allocated and deallocated at execution time by
means of two special operators, new and delete.
The HEAP -- the Free Store
A pool of memory locations reserved for allocation and deallocation
of dynamic data.
new <type>;
new <type> [<int expr>];
int * returnValue;
returnValue = new int[40]; // Create an array of 40 integers
delete ;
delete [] ;
- Memory leak
- the loss of available memory space that occurs when
dynamic data is allocated but never deallocated.
- Inaccessible Object
- a dynamic variable on the free store without any
pointer pointing to it.
- Dangling pointer
- a pointer that points to a variable that has been
deallocated.
Examples
int* ptr1 = new int;
int* ptr2 = new int;
*ptr2 = 44;
*ptr1 = *ptr2;
ptr1 = ptr2; // what ptr1 originally pointed becomes inaccessible,
// should delete ptr1 first
delete ptr2; // ptr1 becomes dangling,
// can be avoided by : ptr2 = NULL;
Dynamic Data Examples
class Person {
public:
string name; // Person's name
int age; // Their age
}; // Note the annoying semi-colon!!
Person Me; // Declare a person
Me.name = "Chang"; // set their name
Me.age = 25; // and age
class Person {
public:
string name; // Person's name
int age; // Their age
Person * father; // Pointer to father
Person * mother; // and mother
};
Person * Human;
Human Alice, Bob; // is same as
// Person * Alice, * Bob;
Making new People
Person * Alice;
Alice = new Person;
Alice->name = "Alice"; // is same as
// (*Alice).name = "Alice";
Alice->age = 20; // (*Alice).age = 20;
We can make parents for Alice:
Alice->father = new Person;
Alice->mother = new Person;
And we could continue making ancestors ...
(Alice->father)->father = new Person;
((Alice->father)->father)->mother = new Person;