For the first part:
Your test() function is trying to return the address of a local variable. This is essentially junk after the function is over, and you should not do this.
When you first allocated ptr to hold the double, this allocates memory. You then reassign ptr to point to a static object (not dynamically allocated). As soon as you do this, the
link to your dynamically allocated memory is lost, AKA a memory leak.
When you now call
delete ptr
, ptr is currently pointing to some statically-allocated memory, and you can't delete that. What you were
trying to delete was already lost on line 9.
Second question part:
Perhaps you should read into what the scope of a variable is. the variable "ptr" only exists in your test function. That being said, the
memory it points to is dynamically allocated and therefore still exists after the test() function ends.
In your main function, when you call test(), you do
nothing with its return value. This is another memory leak. Instead, you'd want to assign it to something (it's returning a pointer to a double, right?).
To properly return and delete something, you'd do
1 2 3 4 5 6 7 8 9 10 11
|
double* test()
{
double * ptr = new double(42);
return ptr;
}
int main()
{
double * dptr = test();
delete dptr; // no memory leak now!
}
| |
_______________________________
The downside to this is that now the user of the the test function has to know what's inside it, and has to remember to manually, explicitly delete it. Not sure how much C++ you know, but one of the amazing things about classes are destructors, where written calls to delete will be done automatically once an object goes out of scope.