Is memory used by variables declared in a function cleared upon return?

I know that variables that are declared within a function are local to that function only. But are those variables also destroyed, resulting in freeing up the space they used, upon return to the main code from that function?

Not really destroyed, but the stack memory space that they used is de-allocated as the stack pointer is restored, and the next function call may overwrite them. It is no longer possible to reference them normally once the function returns. A stack dump may show the values if they haven't been modified by subsequent calls.

A special case is if you declare a variable as static. It exists even after the function it is declared in has returned to its caller (gone out of scope) and any existing pointers to that variable will still work.

1 Like

Thanks for the information. That was very helpful.

Well.. Unless you use new() or malloc() then they stay around 'till you delete() or free() them.

-jim lee