|C++| Dynamic Memory.

Posted Oct 16, 2009 by Codename / comments 0 comments / Print / Font Size Decrease font size Increase font size

Short explanation and examples of dynamic memory allocation in c++.

Generally, when you are coding, you have to specify the amount of variables that will be in your program, but, after compiling, you cannot change the quantity of them. The dynamic memory allows us to allocate memory (from the heap) and free it while our program is running.

For that, we are going to use the new and delete operators and some pointers. Always remember to free the memory allocated, otherwise there will be a memory leak. The types must be the same.

float* ptrNewVariable = new int;           //Wrong.
float* ptrNewVariable = new float;        //Right.

int* ptrNewVariable = new int;    //We have a new int variable

delete ptrNewVariable;            //We free it.


Example: We are doing a game, so we ask the player how many monsters he would want to fight with.

nt main()
{

cout << “How many monsters?” << endl;

int nNumber;

//Store the number in a variable
cin >> nNumber;

//We declare a pointer that will point to a CMonster object. CMonster is an hypothetical class.
CMonster* ptrMonsters  = new CMonster[nNumber];

//To access the objects:
ptrMonsters[ index ]->Fight();        //Just like a normal array.


//When we are finished we free the memory.
delete[]  ptrMonsters;                //Remember the array form of delete.


ptrMonsters = NULL;                    //We set it to null so it will not be pointing to memory that is not allocated.

return 0;

}

Remember :

-          When we use  new , we must use delete.

-          When we use  new[], we must use delete[].


Avoid memory leaks.

Situation 1.

void Search()
{

int* ptrNewVariable = new int[5];    //New dynamic allocated variable.

//We didn't use delete[] ptrNewVariable. Oopss.

//End of function. The pointer is deleted and the memory address is lost. Memory leak.

}


Situation 2.

int* ptrNewVariable = new int;    //The pointer holds the variable address.

ptrNewVariable = new int;        //Memory leak here, the pointer holds the new variable address,
//but lost the previous one, so you will not be able to free it.

delete ptrNewVariable; //Delete the last one allocated memory, but not the first one.

Rate this Article:

Be the first to rate me.

  • Nothing Found!

    Why not submit your own content? Signup here.


* You must be logged in order to leave comments, please login or join us.

Comments

No comments yet.



Bookmark and Share
Sign up for our email newsletter
Name:
Email: