0

From this question I understand that in C# after the end of scope in most cases the garbage collector collects the variables.

But in C++ there is no garbage collector, yet I still can do this:

{
    int a = 0;
}

{
    int a = 10;
}

What happens with the variables in the memory at the end of the scope with C++?

Community
  • 1
  • 1
Bonnev
  • 947
  • 2
  • 9
  • 29
  • This is a question well-answered in any [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). See also [this question](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). – chris Nov 30 '13 at 23:40
  • They stay there (and you cannot reach them) until they get overwritten. Usually we don't care. – Jongware Nov 30 '13 at 23:40
  • The local variables reside on the stack, and get overwritten when the stack pointer reaches there again. – SwiftMango Nov 30 '13 at 23:42
  • your example is bad, garbage collector will not kick in in C#. The variable likely just reside in a register. – yngccc Nov 30 '13 at 23:43
  • (Addendum) In your specific example, an optimizing compiler may notice the variable is unused inside its scope and never emit the code that writes them to memory. – Jongware Nov 30 '13 at 23:44
  • 1
    Well talking straight, there is no destructor here (cause there are not a class at all), this is a behavior inherited from C where `{` create a scope, and a new memory level in stack, but when you exits that scope `}`, all memory in that stack is released to the system. – Rafareino Nov 30 '13 at 23:48

2 Answers2

3

You do not need a garbage collector for this. This is done in the stack. whenever you are done from the first one it is going to overwrite it with the second one. The only thing that you have to wary about is the variables that declared using new or malloc. When using new or malloc, the variables will be stored in the heap. if you do not delete or free the unused variables you will have memory leak.

user1061392
  • 304
  • 3
  • 14
  • 1
    "variables will be stored in the heap" -> the *memory* that is pointed to by the variables is in the heap, and so it's inaccessible when you loose the variable that point to it. – Jongware Nov 30 '13 at 23:55
1

After exiting the scope local variables are desytoyed. If the type of a local carible is a user defined type then the destructor is called.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335