Home > OOP344 > Dynamic Memory Management Overview with C++ 1

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;
iPtr = new int;
*iPtr = 10
cout << *iPtr << endl
delete *iPtr //simply remove the allocated memory pointed by *iPtr
}
Keep in mind that “delete *iPtr” does not delete the pointer, but it deletes what is it pointing to.
Categories: OOP344
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: