Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie question on memory

Status
Not open for further replies.

Dreadson

Instructor
Jun 11, 2003
63
US
My question is one concerning memory allocation in C++

Say you declared a variable -

int p = 5;

The compiler allocates bytes in memory for data type integer; but does it automatically free that memory after the program is done, or do you have to use the new and delete operators for every variable you declare?

My main concern is: how do you manage memory in C++, and how much is automatic or up to you?
 
Variables that are declared without new (ex. int i = 5;) will be automatically deleted when they go out of scope.
Any pointers that you allocate memory to using the new operator are your responsibility to delete.
Ex.
Code:
int*  pInt = new int;
char* pStr = new char[ 40 ];
...
delete pInt;    // Use delete for non-array pointers.
delete [] pStr; // Use delete [] for array pointers.
 
If it is declared on the stack, then it is deleted when it goes out of scope.

If it is declared on the heap (i.e. new), you are responsible for it.

The only exception to heap stuff is the STL template for auto_ptr. These get wiped when they go out of scope.

That is normal C++. There is also managed C++ which comes from M$ (Visual Studio 2002 onwards). Managed basically means that it reference counts your variables and deletes them when they are no longer used. You should not delete anything if you use this variant. This is a M$ only non portable variant. I haven't checked but it is possible that other development systems like CodeWarrior and MinGW also support this variant on M$ platforms.
 
This is when knowledge of low level function representation comes in handy. Knowing that local variables are always kept on stack, which is "wiped" after the function exits, etc. will never make you ask anything like this anymore.

And regarding managed memory - it's possible on modern machines, with loads of memory :) Of course, you can never mind freeing something, when you have 1024 MB of RAM. But if you run on a limited memory, you still need to call Dispose whenever possible, because Trash Collector works on his own and frees memory not always as the programmer might expect.

------------------
When you do it, do it right.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top