【发布时间】: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++ 中,您应该使用
new和delete而不是malloc和free。即便如此,比起new/delete,更喜欢容器和std::make_unique或std::make_shared。此外,使用前缀字母 c 包含 c 标头,例如#include <cstdio>而不是#include <stdio.h>。 -
你不能在这里使用负索引。
-
你应该避免在 C++ 中使用
malloc/free。new/delete是手动分配内存的 C++ 方式。也就是说,std::vector、std::unique_ptr或std::shared_ptr应该是首选。 -
您最多只能写信至
test[0]test[2*n]。你用j =-n写出界外。不要违反程序约束,它不会破坏。 -
另外,你不测试
malloc是否返回空指针