Why can't I reclaim my dynamically allocated memory using the "delete" keyword?
Posted
by
synaptik
on Stack Overflow
See other posts from Stack Overflow
or by synaptik
Published on 2012-04-10T23:23:07Z
Indexed on
2012/04/10
23:29 UTC
Read the original article
Hit count: 296
I have the following class:
class Patient {
public:
Patient(int x);
~Patient();
private:
int* RP;
};
Patient::Patient(int x) { RP = new int [x]; }
Patient::~Patient() { delete [] RP; }
I create an instance of this class on the stack as follows:
void f() { Patient p(10); }
Now, when f() returns, I get a "double free or corruption" error, which signals to me that something is attempted to be deleted more than once. But I don't understand why that would be so. The space for the array is created on the heap, and just because the function from inside which the space was allocated returns, I wouldn't expect the space to be reclaimed.
I thought that if I allocate space on the heap (using the new keyword), then the only way to reclaim that space is to use the delete keyword. Help! :)
© Stack Overflow or respective owner