二维阵列内存泄漏 - 应该很容易,我觉得很愚蠢

时间:2011-08-24 21:22:23

标签: c++ c memory 2d

非常简单的代码:

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);

当我评论这些行时 - 没有内存泄漏。当它们存在时 - 内存泄漏。希望我只需要另一双眼睛,因为我不能为我的生活看到什么是错的。

1 个答案:

答案 0 :(得分:4)

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

但是,由于您使用的是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)的索引。

干杯&amp;第h。,