user2630015
user2630015

Reputation:

Where do function variables go to?

When I'm declaring a variable in a function, I'm using some memory. When the function is done doing it's job, is the memory getting freed?

Upvotes: 1

Views: 141

Answers (2)

RMo
RMo

Reputation: 132

Perhaps most importantly is you understand the concepts of a stack and a heap and this post as very good explanations on the subject:

What and where are the stack and heap?

Cleverness aside (auto_ptrs and the like), the gist of it is that if they are allocated in the stack then they are freed when they leave the scope, otherwise you need to take care to free them yourself. If you understand the above you'll get a better understanding of what to look for.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258608

All automatic storage variables will be freed when they go out of scope, and you have to be explicit about dynamically allocated ones:

void foo()
{
    int x;
    int* y = new int;
    //You get a memory leak with each call to foo without the following line
    delete y;
} //x is freed here

Upvotes: 6

Related Questions