Sign in to follow this  

noob heap/stack question

This topic is 2843 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Alright, so local variables are created in the stack, and variables declared with new should be in the heap (if i'm not mistaken). What happens when you declare a local variable with new? Should you delete it at the end of your method, or will it be removed after the method exits?

Share this post


Link to post
Share on other sites
Quote:
Original post by Hodgman
Everything that you allocate with new must be deallocated with delete, otherwise you've got a memory leak.


That is what I thought, but I wasn't positive as most questions having to do with heap/stack are more along the lines of answering what they are rather than more specific things about them.

Thanks much! Answered :D

Share this post


Link to post
Share on other sites
Here's the problem with your understanding: You don't "declare" variables with 'new'; you allocate them.

When you use 'new', space for the variable is allocated, and a pointer is returned. You can then assign the pointer to a local variable. This local variable is on the stack; it points (being a pointer) to the allocation, which is on the heap.

At the end of the variable's scope, it is automatically cleaned up, because it's on the stack. The thing that it points at is not automatically cleaned up. This can be bad; if you haven't saved the pointer value somewhere else, then now you don't have anything which points to the allocation, which means you don't have a way to deallocate ('delete') it. The memory will be wasted ("leaked") until the end of the program, and the destructor for the object won't get a chance to run.

As you can imagine, this kind of thing gets tricky rather quickly. Fortunately, you don't have to wrestle with it yourself. Instead, use tools such as smart pointers and standard library containers.

Share this post


Link to post
Share on other sites
Quote:
Original post by kirby900
How does using Standard Library containers help? Do vectors, lists, etc. automatically invoke delete on pointers when the container goes out of scope?


Standard Library containers help because they manage their memory themselves, not because they delete the pointers they contain. For this, the Standard Library has smart pointers.

Share this post


Link to post
Share on other sites

This topic is 2843 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this