【发布时间】:2022-07-22 01:33:49
【问题描述】:
这是我在执行 .exe 文件时遇到的错误。
*** Error in `./test_bin.exe': realloc(): invalid old size: 0x00007ffc67d00cf0 ***
我不明白为什么当我按预期使用 realloc() 时会引发错误。我曾尝试在 realloc() 调用之前进行强制转换,但这也不起作用。
int main{
double *test;
double arr1[5] = {1.0,2.0,3.0,4.0,5.0};
double arr2[2] = {1.0,2.0};
int i;
test = (double*)malloc(5*sizeof(double));
test = arr1;
for(i=0;i<5;i++) printf("%lf ",test[i]);
printf("\n");
test = realloc(test,2*sizeof(double));
test = arr2;
for(i=0;i<2;i++) printf("%lf ",test[i]);
printf("\n");
return 0;
}
【问题讨论】:
-
您只能重新分配从 malloc 等获得的堆指针。在
test = arr之后,您的指针现在指向堆栈上的一个数组。你不能重新分配它。 -
您在通过覆盖
test指针分配内存后立即泄露了malloced 内存 -
test = (double*)malloc(5*sizeof(double)); test = <<anything other than test self-assignment>>.是两行的瞬时内存泄漏。