2D数组内存泄漏-应该很容易,我觉得愚蠢

2D Array Memory Leak - Should be easy, I feel stupid

本文关键字:很容易 内存 数组 泄漏 2D      更新时间:2023-10-16

很简单的代码:

signed int **ifftResults = (signed int **)malloc(sizeof(signed int *) * recordsPerBuffer);
for (int i=0; i < recordsPerBuffer; i++)
{
    ifftResults[i] = (signed int*)malloc(sizeof(signed int) * fftLength);
}

之后:

for (int i=0; i < recordsPerBuffer; i++)
{
   free(ifftResults[i]);
}
free(ifftResults);

当我注释掉这些行时-没有内存泄漏。当它们存在时——内存泄漏。希望我只是需要另一双眼睛,因为我这辈子都看不出哪里出了问题。

我写这篇文章时给出的代码似乎不足以回答"为什么"这个问题。

但是,由于您使用的是c++,您可以通过使用std::vector来确保没有内存泄漏。

一样:

// Allocation.
std::vector< std::vector< int > >  fftResults( recordsPerBuffer, std::vector< int >( fftLength ) );
// Usage:
fftResults[y][x] = blah;
// Deallocation: automatic.
另一种实现矩阵的方法是
std::vector< int >  fftResults( recordsPerBuffer*fftLength );

,然后计算给定(x,y)的索引

干杯,hth。