lo tolmencre
lo tolmencre

Reputation: 3934

Delete Derived Class with Stack Pointer?

So stack memory cannot be manually be freed up via delete, because this somehow induces UB. But when creating a derived class object, the "new"-keyword is involved. Say for example:

void some_function(){
    Base* base;
    base = new Derived;
}

As "new" is involved, is base = new Derived now located on the heap? And if so, does the memory where it is located, need to be freed up manually again? Or is it located on the stack and the memory will be freed up after the program terminates anyway?

Upvotes: 1

Views: 43

Answers (2)

Bill
Bill

Reputation: 14685

When dealing with pointers, don't confuse the memory the pointer takes with the memory the pointer is pointing at.

In your function, base is a function local variable, and it will be cleaned up when it goes out of scope. However, the memory base points at will not.

Before allocation: 
--------
| base |
--------
freed at end of scope

After allocation:
--------                    ---------------
| base | ===============>   | new Derived |
--------                    ---------------
freed at end of scope       Will not be freed

However, if you add in delete base; to your function:

--------                    ---------------
| base | ===============>   | new Derived |
--------                    ---------------
freed at end of function    freed by "delete base;"

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 993015

The rule is: Any time you use new, you must free the memory with delete. The only exception is for something called "placement new" which is rarely used (see comments).

In your case, the pointer called base is itself located on the stack. However, what it points to is allocated on the heap.

When your program terminates, all of its memory will be freed by the kernel. It doesn't matter where or how the memory was allocated.

(Note to pedants: I am using "stack" and "heap" here as per common usage, notwithstanding the fact that those terms are not mentioned in the C++ standard.)

Upvotes: 4

Related Questions