堆栈上的内存泄漏 [英] Memory leak on the stack
问题描述
是否可以通过非常糟糕的设计在C ++中创建内存泄漏而没有堆分配?
Is it possible to create memory leak in C++ without heap allocation, through very bad design ?
我想到的一个例子,如果它不符合我的预期,请纠正我:
One example I had in mind, please correct me if it does not do what I think it does:
#include <iostream>
#include <string>
void WhatIsYourName()
{
std::string name;
std::cout << "What is your name? ";
getline (std::cin, name);
std::cout << "Hello, " << name << "!\n";
WhatIsYourName();
}
int main()
{
WhatIsYourName();
}
对我来说,WhatIsYourName()
似乎在每次调用时都初始化一个新的std::string name
,但是该函数从未真正超出范围,因此从不释放内存.
是对的吗 ?还是编译器足够聪明,以至于将来不会使用该变量,因此它在不超出函数范围的情况下将其删除?
To me it looks like WhatIsYourName()
is initializing a new std::string name
on every call, but the function never really goes out of scope so the memory is never released.
Is that right ? Or is the compiler smart enough to see that the variable will not be used in the future, so it deletes it without the function going out of scope ?
仅使用堆栈分配,还有哪些其他不良设计会造成内存泄漏?
What kind of other bad design would create a memory leak using only stack allocation ?
推荐答案
您有一个不会停止的递归调用(没有退出条件),因此每次调用函数都会创建一个新的堆栈页面,直到程序由于堆栈溢出而崩溃.编译器无法对其进行优化.
You have a recursive call that doesn't stop (there's no exit condition), so a new stack page is created for every function invocation, until of course the program crashes due to stack overflow. The compiler cannot optimize that away.
关于最后一个问题,是否有可能在没有堆分配的情况下(并且没有这种无限递归的情况)造成内存泄漏,我相信不是,局部变量会自动释放,这就是为什么这种存储持续时间是称为 自动存储期限 .
Regarding your last question, whether is possible to create a memory leak without heap allocation (and without this kind of infinite recursion), I believe it is not, the local variables are automatically released, that's why this type of storage duration is called automatic storage duration.
这篇关于堆栈上的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!