-
dynamic memory
Just been reading about the new and delete keywords and i made the following simple code
Code:
// dynamic memory allocation
#include<iostream>
using namespace std;
int main(void)
{
int* pAge=new int;
if(pAge == 0)
{
cout << "Sorry no memory available!" << endl;
return(0);
}
*pAge=27;
cout << "Address=" << pAge << endl
<< "Contents=" << *pAge << endl;
return(0);
}
Notice i havent used a delete here to free the memory.
How come this doesnt prompt an error or at least a warning on my compiler ?(MSVC++ 6.0)
I would have thought whereever there is a new there must be a delete ?
-
You have just created a memory leak. It is up to the programmer to "clean" the memory up after you have used it.
Yes, every time you use the keyword new there should be a corresponding delete.
-
Yeah i appreciate that but i thought a compiler would at least be able to count the number of news in a program and the number of deletes and if the numbers dont match issue a warning.
-
Or you could use an auto_ptr which would not need a delete at the end of the code:
Code:
#include <iostream>
#include <memory>
using namespace std;
int main(void)
{
auto_ptr<int> pAge( new int );
if( pAge.get() == NULL )
{
cout << "Sorry no memory available!" << endl;
return(0);
}
*pAge=27;
cout << "Address=" << pAge.get() << endl
<< "Contents=" << *pAge << endl;
return(0);
}
If the program is successfull in allocating space for the integer, then it will automatically be freed without the need for a delete to be called prior to the return statement. You do need to remember to do things a bit differently however as noted in blue above. The get member gets the address of the pointer.
-
Even better. check out the smart pointer classes available here.