Reputation: 1374
I have a doubt related to the pasted code. I have allocated memory for an int and deleted(as usual). But somewhere i see this sysntax(line 1) which allocates an anonymous int space. How to free this space, isn't this result in memory leak?
main(){
int *p = new int;
new int;
if(p)
delete p;
system("PAUSE");
return 0;
}
Upvotes: 0
Views: 155
Reputation: 6834
Well, this is C++, so unavoidable
is a (slight) overstatement.
"All" you need to to is replace global operator new
, and have that keep track of allocations.
Now: I can't imagine doing this is real code, but doing the equivalent for class types only is something done in practice (although I don't imply that it's best practice!)
For example, this (otherwise quite silly) code does not leak .
int count = 0;
void* operator new (size_t size)throw(std::bad_alloc)
{
if (size == sizeof(int))
{
++count;
if (count == 2)
return &count;
}
return malloc (size);
}
void operator delete (void *p)throw()
{
if (p != &count)
free(p);
}
int main()
{
int *p = new int;
new int;
delete p;
system("PAUSE");
return 0;
}
Upvotes: 0
Reputation: 64682
If you allocate memory, and deliberately choose not to hold a pointer to it, then you cannot free it.
C++ gives you enough rope to hang yourself with, and allows you to aim a gun at your own foot.
That is nothing new.
The other mistake is checking the value of p
to see if it was allocated successfully.
Only on older compilers does new
return NULL
if it fails. On newer compilers, a failed new
will result in throwing a std::bad_alloc
exception.
So in this code, (assuming you are using a compiler from the last decade) you know that either:
new
succeeded, and p
is valid/non-NULL.There is no way for p
to end up NULL
!
Even if p
could end up NULL, calling delete
on a NULL
value is perfectly safe, and there is nothing wrong with it.
So your example code could well be:
int main()
{
int *p = new int; // Will throw exception if fails
new int; // Deliberate Mem Leak
delete p; // No need to check NULL
system("PAUSE"); // Pause to see results (NOTE: this is skipped if an exception is thrown!)
return 0;
}
Upvotes: 14