Dynamic Memory

When programs are created with variables of a pre determined / fixed size, the overall program has a fixed size and uses a specific amount of memory at run time.

 

However when variable sizes are unknown, say for multiple objects being created or for user input (e.g. text form entry), it is not possible to pre-determine the memory requirements as, for example, we will not know how many objects will be created or how many characters a user may enter into a text form. We therefore need a method to create (and delete) memory 'on the fly', at run time.

 

The technique to allocate new storage at run time is known as Dynamic Memory management, and utilises the operator keywords, new and delete to allocate and deallocate storage, as required.

 

It is very important to ensure that storage is deallocated using the operator keyword delete, in order to stop memory leaks!

 

Storage is dynamically allocated using the operator keyword new followed by the data type, which returns a (void) pointer to address space on the heap.

 

For example, int *ptr = new int  ; declares an int pointer, which will be assigned the address returned by new at runtime. We can then assign values to the dereferenced *ptr as follows: *ptr = 555 ;  //just as an example.

 

Once used, we delete the storage space using the operator keyword delete as follows: delete ptr ;

 

#include <iostream>
using namespace std;

int main() {

	int *myPtr ;  //just showing two techniques to assign new to  pointer
	myPtr = new int ;

	int *ptr = new int ;  //and here's the second version

	cout << "Please enter an integer: " << endl ;
	cin >> *myPtr ;

	cout << "Please enter another integer: " << endl ;
	cin >> *ptr ;

	cout << *myPtr << endl ;
	cout << myPtr << endl ;

	cout << *ptr << endl ;
	cout << ptr << endl ;

	delete myPtr ;

	delete ptr ;

	return 0;
}

Compile & Run:

Please enter an integer:
63
Please enter another integer:
49
63
0x3f1130
49
0x3f1140

 


 

 

Similarly, the operator keywords new[ ] and delete[ ] are used to allocate/deallocate storage for arrays:

#include <iostream>
using namespace std;

class myClass {

	public:
		myClass() {
			cout << "Constructor called!" << endl;
		}
		~myClass() {
			cout << "Destructor called!" << endl;
		}
};

int main() {

	myClass *myObject = new myClass[3];  //remembering new returns a pointer

	cout << myObject << endl ;  //just showing this is the same as first element 0

	for (int i = 0; i < 3; i++) {
		cout << &myObject[i] << endl ;
	}

	delete[] myObject ;

	return 0;
}

Compile & Run:

Constructor called!
Constructor called!
Constructor called!
0x711134
0x711134
0x711135
0x711136
Destructor called!
Destructor called!
Destructor called!

Leave a Reply