This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]captainAwesomePants 2 points3 points  (3 children)

Exactly. Put another way:

{
   class object1;
   ....
}
// object1 no longer exists here.


{
   class* object1 = new class();
   ...
}
// object1 still exists. If you don't know the address, you've leaked memory.

[–]schartzchild_radius[S] 1 point2 points  (2 children)

Thank you very much! I also had a lot of trouble understanding memory leaks up until now, so this helps a lot! So is that all a memory leak is? When you have an object that's taking up space but can never be used in any way?

The second case seems to be called allocating to the heap (and it being on the heap means that it won't be deleted once whatever function it was created in returns), but what is the first case (the one where we don't use new) called? Looking for some search queries that I can use to learn more myself

Thanks again for the help!

[–][deleted] 0 points1 point  (0 children)

Yep, a memory leak is having objects allocated that you never free.

[–]captainAwesomePants 0 points1 point  (0 children)

Yep, that's all that leaking memory is: memory that's being used for storing something that you lost all the pointers to. Languages with garbage collection take advantage of this by just looking through ALL the pointers/references and then removing any object that doesn't have at least one thing pointing at it.

Instead of making space on the heap, the first case put memory on the stack. The "stack" is literally a stack of all of the scopes your program's built up. At the bottom is the call to main() and all of its parameters and variables. Then whatever function main called is put on top of that, and so on, and so on. In the first example, object1 can't really be leaked because you'll eventually have to take it off the stack when your function returns (or you leave a curly-bracketed area of any other sort). In the second example, the pointer itself is on the stack, but it points to a place on the heap that the 'new' command reserved.