我正在尝试使用一个函数来分配一个复杂的双数组,执行一些操作并返回最后计算的值。虽然计算很好,但当我试图释放分配的空间时,我遇到了问题。在执行过程中,我得到了"双倍空闲或内存损坏"的错误。我正在使用标准库。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
#include <assert.h>
double complex main()
{
// Declare fixed number of steps.
int number_of_elements=10;
// Reserve memory for array.
double complex *complexArray = calloc(number_of_elements,sizeof(double complex));
// Verify if allocation was successfull.
assert(complexArray!=NULL);
// Fill first position with number and start counting
complexArray[0]=1+2*I;
int i=0;
for (i=0;i<number_of_elements;i++)
{
complexArray[i+1]=2*complexArray[i]; // Simple operation
printf("The complex number stored in position %i is %f+i%fnn",i+1,creal(complexArray[i+1]),cimag(complexArray[i+1])); // Print the current number
}
double complex output=complexArray[i];
assert(complexArray!=NULL); // Check if pointer is not NULL again
free(complexArray); // Program fails here
complexArray=NULL;
return output;
}
我把数据类型从"双重复杂"改为"双重",它就起作用了。有没有办法释放复杂的数组?
您在分配的内存后面写入。最后一个循环迭代使用i=9
并写入不在您分配的范围内的complexArray[i+1]
。free()
本身似乎没有什么问题。
像这样的问题应该可以通过valgrind来发现。
关于双复数*complexArray=calloc()的free()看起来是正确的。请记住,数组是从0开始的零,请仔细检查您的索引,特别是:
complexArray[i+1]=2*complexArray[i];//操作简单的
因为这将导致第一输出为:存储在位置1 中的复数
我想您的循环可以以这种方式抛出EXC_BAD_ACCESS。