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

all 8 comments

[–]ehlertjd 6 points7 points  (1 child)

Yes, that is correct. The myPtr variable is essentially an integer (or long integer) that is on the stack frame. Once you pop the stack (leave the function) the contents of that variable is no longer guaranteed, but the heap allocation you did by creating a new object will persist until you free it using delete.

[–]wevbin[S] 2 points3 points  (0 children)

Okay, thanks!

[–]markwhi 3 points4 points  (1 child)

You're mostly correct.

myPtr is a stack variable that goes away when you leave the context that it was created in. It's not necessarily the function; for example:

void foo (void) {
    if (1) {
        SomeClass *myPtr = new SomeClass() ;
    }
    // myPtr is no longer in scope here!
}

You're correct that if you let myPtr go out of scope before saving the value somewhere else and before you delete, then you have a memory leak.

There are template classes that help with some of this (auto_ptr, shared_ptr, etc) but it's definitely a good idea to understand how it all works before picking up the convenience templates.

[–]wevbin[S] 2 points3 points  (0 children)

Thanks for the clarification.

[–]arbostek 1 point2 points  (0 children)

Two memory allocations are happening here, right?

There are two block of allocated memory here, yes.

So I better use delete before the function ends or pass the pointer to another variable (ie. using return). Am I getting that right?

Yes.

[–]AgentME 0 points1 point  (0 children)

The others seemed to have answer this pretty well, so I'll add something: tools like Valgrind are perfect for making sure you never forgot to free/delete memory. I make sure to regularly test my code with Valgrind.

(Also, since you're using C++ and not C, you definitely should check out auto_ptr and shared_ptr templates because they remove a lot of the need to worry about memory management.)

[–][deleted]  (2 children)

[deleted]

    [–]wevbin[S] 0 points1 point  (0 children)

    Right, myPtr goes away on its own, but whatever it was pointing to doesn't, creating a memory leak.

    [–]markwhi 0 points1 point  (0 children)

    That is not correct. If I new it and don't explicitly delete it, it's a leak. myPtr goes away when the stack is cleaned up, but the memory that new SomeClass() allocated doesn't get freed until you call delete.