Dynamic Memory Management Overview with C++ 1
Allocating memory
Dynamic Memory allocation is done by using the keyword “new” in c++. When creating dynamic memory a pointer is always needed. Let us start by looking at one very simple example. (the code below does not deallocate memory which I will get to next.)
main(){ int* iPtr;
iPtr = new int;
*iPtr = 10 cout << *iPtr << endl }
so there you have it, a simple dynamically allocated int. The program above does not give us any advanges, but I used it since its a good example for learning purposes.
Deallocating memory
It is very important to give the memory back to the OS after we are done with the memory we need. Memory is given back to the OS by using the keyword “delete”. It is very simple to use, in the example I did not deallocate memory back to the OS, which makes it unusable until the OS is restarted. Here is an modified version of the program above which deallocates memory.
main(){ int* iPtr;Keep in mind that “delete *iPtr” does not delete the pointer, but it deletes what is it pointing to.
iPtr = new int;
*iPtr = 10 cout << *iPtr << endl delete *iPtr //simply remove the allocated memory pointed by *iPtr }