【问题标题】:Errors if free() is called after malloc() in C++如果在 C++ 中的 malloc() 之后调用 free(),则会出错
【发布时间】:2017-03-27 20:11:11
【问题描述】:

我为我称为 test 的数组分配空间,它将有 (2*n + 1) 个 double 类型的元素。我填充数组,最后我 free() 它。但是如果我使用 free(),我会得到一个错误:“double free or corruption(out): 0x0000000000000f1dc20”。如果我评论 free(),代码就会运行。我无法发现问题。

using namespace std;
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

long    n=512; //grid size
double *test;

int main() 
{
    test = (double*) malloc(sizeof(double) * (2*n+1));

    for (long j=-n;j<=n;j++)
    {
        test[j] = double(j);
    }

    free(test); //<--- gives me error if I use this
    return 0;
 }

【问题讨论】:

  • 这是 c 和 c++ 的完美结合。在 c++ 中,您应该使用 newdelete 而不是 mallocfree。即便如此,比起new/delete,更喜欢容器和std::make_uniquestd::make_shared。此外,使用前缀字母 c 包含 c 标头,例如 #include &lt;cstdio&gt; 而不是 #include &lt;stdio.h&gt;
  • 你不能在这里使用负索引。
  • 你应该避免在 C++ 中使用malloc/freenew/delete 是手动分配内存的 C++ 方式。也就是说,std::vectorstd::unique_ptrstd::shared_ptr 应该是首选。
  • 您最多只能写信至test[0] test[2*n]。你用j =-n写出界外。不要违反程序约束,它不会破坏。
  • 另外,你不测试malloc是否返回空指针

标签: c++ memory malloc


【解决方案1】:

不,那样不行。

您为 2n 的双精度数组分配了足够的空间,但 C 定义了范围为 [0..2n-1] 的数组索引。您不能任意决定使用 [-n..+n] 访问元素。正如在 cmets 中已经描述的那样,它是Undefined Behavior

如果你需要做你似乎正在做的事情,你将不得不为所有访问使用一个偏移量,例如:

test[j+n] = double(j);

这样您就有更好的机会不破坏堆结构,从而从 C 和/或 OS 内存管理器中收到烦人的错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 2021-12-11
    • 1970-01-01
    • 2020-12-10
    • 2010-11-06
    • 2014-05-21
    • 2011-06-06
    相关资源
    最近更新 更多