C ++ static array leading to memory leak?

Say I have something like ...

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

When foo is called, it creates an array on the stack, and when it goes out of scope, is memory freed automatically? Or is c destroyed, but the memory remains allocated, without the ability to access / get it, except for restarting the computer?

+5
source share
4 answers

- is memory freed up automatically?

Yes. And destructors will also be called if you're interested. That's why they are in a automatic storage class .

( 100 ( ), 100 * sizeof(T) "".)

+6

, . - :

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

, .

! , . ().

+4

, ; . , , . , . , , , , .

+3

.

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

0
source

All Articles