我对C编程很陌生,我无法找到解决问题的方法。尽管代码可以工作(我已经能够将它包含在其他程序中),但是当它试图释放calloc()分配的内存时,它会返回以下错误:
free(): invalid next size (normal):跟着看上去是一个内存地址。我正在使用mpc库(用于任意精度的复数)。这是重复错误的最小程序:
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
#include <mpfr.h>
#include <mpc.h>
int N = 10;
int precision = 512;
int main(void) {
mpc_t *dets2;
dets2 = (mpc_t*)calloc(N-2,sizeof(mpc_t));
for (int i = 0; i<=N-2; i++) {
mpc_init2(dets2[i],512); //initialize all complex numbers
mpc_set_str(dets2[i],"1",0,MPFR_RNDN); //set all the numbers to one
}
free(dets2); //release the memory occupied by those numbers
return 0;
}谢谢你的帮忙!
发布于 2015-04-22 14:17:35
您的for循环在i == N-2之后中断,但应该在此之前中断。for循环中的条件应该是i<N-2而不是i<=N-2。
因此,您尝试访问内存,这是超出界限的。这将导致undefined behaviour,因此任何事情都可能发生,包括分段错误、自由运行时错误或什么都没有。
https://stackoverflow.com/questions/29799763
复制相似问题