Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Allocating memory on the heap and stack?

Coming from a Java background, I'm still a little confused about allocating memory in C++. I'm pretty sure the first two statements are correct:

void method() {
    Foo foo;    // allocates foo on the stack, and the memory is freed
                // when the method exits
}

void method2() {
    Foo *foo = new Foo();   // allocates foo on the heap
    delete foo;             // frees the memory used by foo
}

But what about something like this?

void method3() {
    Foo foo = *new Foo();   // allocates foo on the heap, and then copies it to the stack?
                            // when the method exits, the stack memory is freed, but the heap memory isn't?
}

Say I added foo to a global array inside method3(). If I tried to access one of foo's data members after the method exits, would that work? And is method3() prone to memory leaks?

Thanks in advance.

like image 882
nebulabrot Avatar asked Feb 24 '13 07:02

nebulabrot


1 Answers

Foo foo(); 

Declares a function by the name foo which returns a Foo object and does not take any arguments. It is known as the most vexing parse in C++. You probably meant:

Foo foo; 

It creates a foo object locally/automatic storage. The object is automatically deallocated once the scope { } in which it is declared ends.


Foo *foo = new Foo();   // allocates foo on the heap
delete foo;

This is true, the object on freestore pointed by foo is deallocated once you call delete. There is no memory leak.


 Foo foo = *new Foo(); 

Allocates a Foo object on freestore and then a copy of that object is used to initialize foo. Since you do not have a pointer to the freestore allocated object, it causes a memory leak. Note that if the destructor of Foo has some code which causes side effects then it is not merely memory leak but undefined behavior.

like image 186
Alok Save Avatar answered Oct 01 '22 23:10

Alok Save