简体   繁体   中英

C++ static array leading to memory leak?

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?

is the memory deallocated automatically?

Yes. And the destructors will be called too, in case you wonder. This is why they're in the auto matic 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".)

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM