即使我在堆上声明内存,void 函数也能防止内存泄漏吗?

问题描述 投票:0回答:1

我目前正在从教科书上学习 C++,显然这段代码不会导致内存泄漏,尽管当我询问 ChatGPT 时,它告诉我事实并非如此。代码很简单,如下:

#include<iostream>
using namespace std;
void FuncOne();
int main() {
    FuncOne();
    system("pause");
    return 0;
}
void FuncOne() {
    int* pVar = new int(5); // this is created on the free store? even after the function is finished, the memory is still there.. (I assume)
    cout << "the value of *pVar is:" << *pVar;
}

*pVar
应该会导致内存泄漏,因为上面没有
delete
吗?也许有人可以向我解释一下是否有我遗漏的东西或者这是作者的一个简单错误?

任何解释将不胜感激!

c++ memory memory-management memory-leaks
1个回答
0
投票

*pVar
应该会导致内存泄漏,因为上面没有
delete

这正是发生的事情。

此外,

cout << "the value of *pVar is:" << *pVar;
具有未定义的行为,因为
*pVar
未初始化,并且在您读取它时持有不确定的值。

© www.soinside.com 2019 - 2024. All rights reserved.