gpt4 book ai didi

c++ - 如何完全删除多维动态数组?

转载 作者:行者123 更新时间:2023-12-02 10:22:56 24 4
gpt4 key购买 nike

实际上我不知道多维数组的大小,可能是

arr[i][k][j]; 

或这样的
arr[i][k][j][l];

或这样的
arr[i];

开始后我会意识到这一点,但我还需要完全删除或清除阵列

我试图这样做
memset(&arr[i][k], 0, sizeof arr[i][k]);

并尝试这样做
delete arr[i][k];

但是该数组仍然没有删除,也许有一个现成的库可以让我执行此操作,请帮忙。
int main() 
{
int M ;
int N ;
int i, j;
int** matrix;
cin >> M;
cin >> N;

matrix = new int*[M];
for ( i = 0; i < M; i++)
matrix[i] = new int[N];

for ( i = 0; i < M; i++)
for ( j = 0; j < N; j++)
{
cout << "Inter element " << "[" << i << "][" << j << "] ";
cin >> matrix[i][j];
}

cout << endl;
for ( i = 0; i < M; i++)
for ( j = 0; j < N; j++)
{
cout << matrix[i][j];
}
cout << endl;
}

最佳答案

使用new SomeType[M]创建数组时,必须使用delete []释放分配给该数组的内存。

对于您编写的2D数组,首先要创建一个指针数组。我们称其为“外部数组”。然后,对于外部数组中的每个元素,再次使用new SomeType[N]创建另一个数组。 new SomeType[N]的返回是一个指针,它将指向相应的“内部数组”。

为了释放“2D数组”中的所有内存,您需要首先为每个内部数组调用delete [],然后再为外部数组调用delete []。不执行任何这些操作将导致内存泄漏。

在您的示例中,您没有任何删除命令,因此我们可以确定内存泄漏。让我们假装我们不知道这一点,并与valgrind一起检查。如果我们使用valgrind传递2和3作为大小的输入来运行可执行文件,则valgrind返回类似

==194743== 
==194743== HEAP SUMMARY:
==194743== in use at exit: 40 bytes in 3 blocks
==194743== total heap usage: 6 allocs, 3 frees, 74,792 bytes allocated
==194743==
==194743== LEAK SUMMARY:
==194743== definitely lost: 16 bytes in 1 blocks
==194743== indirectly lost: 24 bytes in 2 blocks
==194743== possibly lost: 0 bytes in 0 blocks
==194743== still reachable: 0 bytes in 0 blocks
==194743== suppressed: 0 bytes in 0 blocks
==194743== Rerun with --leak-check=full to see details of leaked memory
==194743==
==194743== For lists of detected and suppressed errors, rerun with: -s
==194743== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

valgrind的泄漏摘要清楚地告诉我们,某些内存没有正确释放。
现在,将以下代码添加到主函数的末尾以正确释放所有内存

// Free all the inner arrays. Notice that we call `delete []` passing the
// pointer of an inner array
for ( i = 0; i < M; i++) {
delete [] matrix[i];
}

// Delete the outer array. Notice that now we pass the pointer of the outer array
delete [] matrix;

如果我们再次与valgrind一起运行,则会得到类似
==197046== 
==197046== HEAP SUMMARY:
==197046== in use at exit: 0 bytes in 0 blocks
==197046== total heap usage: 6 allocs, 6 frees, 74,792 bytes allocated
==197046==
==197046== All heap blocks were freed -- no leaks are possible
==197046==
==197046== For lists of detected and suppressed errors, rerun with: -s
==197046== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Valgrind现在告诉我们,我们确实释放了我们动态分配的所有内存。

已释放所有堆块-不可能泄漏

关于c++ - 如何完全删除多维动态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com