views:

189

answers:

5

Lets say I have something like...

void foo()
{
    char c[100];
    printf("this function does nothing useful");
}

When foo is called, it creates the array on the stack, and when it goes out of scope, is the memory deallocated automatically? Or is c destroyed, but the memory remains allocated, with no way to access it/get it back except restarting the computer?

+6  A: 

is the memory deallocated automatically?

Yes. And the destructors will be called too, in case you wonder. This is why they're in the automatic storage class.

(Actually for most architectures the program will only call that 100 destructors (if any), then shift the stack pointer backward by 100*sizeof(T) bytes as "deallocation".)

KennyTM
Ok. Thank you for everyone who replied. I was sure about using new/delete, but someone had given me the impression that what I had posted would not be deallocated.How do you end up in a situation where a pointer gets deleted (when it goes out of scope), but the data it points to remains allocated (inaccessible as well) ?
MDonovin
@MDonovin: See mmr's answer http://stackoverflow.com/questions/2758970/c-static-array-leading-to-memory-leak/2758985#2758985.
KennyTM
A: 

It's gone - all gone.

But the memory is available for use by the next function immediately. the stack is just implemented as a pointer, when you do c[100] it moves the pointer down 100bytes so the next memory requested comes after c. When you leave the function the stack pointer just moves back up to the previous position before you entered the function. This is a very quick and efficent way to manage memory compared to new/delete/malloc

Martin Beckett
+4  A: 

In that case, yes, the memory is deallocated. If you had done something like:

int var = 100;
char* c = new char[var];

Then that would remain behind once the function has ended.

However! You don't have to reboot to get back lost memory on a modern OS. Instead, the memory will be returned once the process (program) ends.

mmr
+3  A: 

To be clear, there isn't really a memory allocation taking place here; there's a stack allocation taking place. The difference is significant because the former requires a function call, reserving memory from the allocation system, and a host of overhead. In contrast, the latter involves just incrementing the stack pointer. Stack allocations are always much, much faster and, except in cases of bugs involving stack corruption, are always cleaned up when your function exits.

Phileosophos
A: 

If the array were truly [function-local] 'static' (i.e., a local variable modified with the 'static' keyword), then for all intents and purposes, the memory would be lost (in use) for the duration of your program (i.e., until the CRT teardown process reclaims the memory after your main() exits).

Jonathan