简体   繁体   English

C ++静态数组导致内存泄漏?

[英]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? 当调用foo时,它会在堆栈上创建数组,当它超出范围时,内存是否会自动释放? Or is c destroyed, but the memory remains allocated, with no way to access it/get it back except restarting the computer? 或者是c被破坏了,但是内存仍然被分配,没有办法访问/取回它,除了重新启动计算机?

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 . 这就是为什么他们在auto存储类中

(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".) (实际上对于大多数架构,程序只会调用100个析构函数(如果有的话),然后将堆栈指针向后移动100 * sizeof(T)字节作为“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. 堆栈只是作为指针实现,当你执行c [100]时,它将指针向下移动100字节,因此请求的下一个内存在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 与new / delete / malloc相比,这是一种非常快速有效的内存管理方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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