C++更正内存泄漏
C++ correcting a memory leak
有人可以帮我弄清楚如何重用一块分配的内存吗?此代码的最终结果应该是对第一个数组初始化和第二个数组初始化使用相同的位置。数组大小为 const 5。
编辑:我想通了。我只需要使用free(nArray);就在"nArray = new int[arraySize + 2];"行之前,这允许我纠正泄漏并重用相同的内存位置。
int main()
{
cout << endl << endl;
int* nArray = new int[arraySize];
cout << " --->After creating and allocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
for (int i = 0; i < arraySize; i++)
{
nArray[i] = i*i;
}
cout << " --->After initializing nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
for (int i = 0; i < arraySize; i++)
{
cout << " nArray[" << i << "] = " << nArray[i] << " at address <" << nArray + i << ">" << endl;
}
cout << endl << " --->Before reallocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << endl;
nArray = new int[arraySize + 2];
cout << dec << " --->After reallocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
for (int i = 0; i < arraySize + 2; i++)
{
nArray[i] = i*i;
}
cout << endl << " --->After reinitializing nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
for (int i = 0; i < arraySize + 2; i++)
{
cout << " nArray[" << i << "] = " << nArray[i] << " at address <" << nArray + i << ">" << endl;
}
cout << endl << " --->Getting ready to close down the program." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
// Wait for user input to close program when debugging.
cin.get();
return 0;
}
你不能这样做。如果要增加数组的大小,可以创建一个具有所需长度的新数组,并将旧数组的所有内容复制到新数组中,或者您可以简单地使用矢量而不是数组。
C++不能保证它将使用哪个内存,并且您没有删除最初分配的内存,这会导致内存泄漏。
相关文章:
- C++功能泄漏内存,我是C++新手,不确定如何解决
- 我的堆栈弹出式磁带的实现是否泄漏内存?
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 析构函数 C++ 使泄漏内存
- 构造函数对象赋值是否泄漏内存
- corba :: orb_init泄漏内存
- Gmock泄漏内存
- 如何在不泄漏内存的情况下删除链接列表
- Visual C ODBC关闭记录集泄漏内存
- 为什么泄漏内存比在动态数组上执行 delete[] 慢
- OpenGL正在泄漏内存.哪个对象未释放
- 可以std ::退出泄漏内存
- uiautomation findall泄漏内存
- 为什么在此OpenCL代码中泄漏内存,为什么要泄漏内存
- pthread在完成后会泄漏内存
- win32 标准::线程泄漏内存
- 返回指向同一变量的指针是否会泄漏内存
- 使用clectType(new any_type())可能会泄漏内存泄漏
- Windows开发:如何确定我的应用程序是否正在泄漏内存
- WinHttp打开泄漏内存