1

我是 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;
}

谢谢你的帮助!

4

1 回答 1

2

您的 for 循环在 之后中断i == N-2,但它应该在之前中断。for 循环中的条件应该是i<N-2而不是i<=N-2.

因此,您尝试访问超出范围的内存。这会导致undefined behaviour,所以任何事情都可能发生,包括分段错误、自由运行时错误或什么都没有。

于 2015-04-22T14:17:35.907 回答