1

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?

  • 1
    have you ever heard about "stack"? - I guess you are talking about basic type, otherwise there could be also used the heap, and it's memory get freed when the var goes out of scope (or alike), if the class provides a correct destructor... (Not if you created the instance with new, of course: in this case it's your duty) – ShinTakezou Jan 08 '14 at 15:21
  • Please don't just go and make assumptions. – Kerrek SB Jan 08 '14 at 15:21

2 Answers2

6

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
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

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.

Community
  • 1
  • 1
RMo
  • 132
  • 7
  • You should read about automatic and dynamic storage duration, because you have misunderstood "stack and heap". – Lightness Races in Orbit Jan 09 '14 at 18:51
  • @Lightness Races in Orbit - It's not that I have misunderstood stack and heap IMO, but you're correct that in C++ terms I should have described it in those terms. In the end your variables can only be in a stack or heap, and you only free those when the stack unwinds or you call deallocation functions, respectively. I do take your point, though! – RMo Jan 10 '14 at 08:37
  • You mean "objects" not "variables" and they can absolutely be in something other than a stack or a heap. _That_'s the point! :) – Lightness Races in Orbit Jan 10 '14 at 16:20