carraysmemorympc

Freeing an array of mpc_t in C


I'm new to C programming and I couldn't find solution to my problem. Although the code works (I've been able to include it in other program), when it tries to free the memory assigned by calloc(), it returns the following error:

free(): invalid next size (normal):

followd by what appears to be a memory address. I'm using mpc libraries (for arbitrary precision complex numbers). This is the smallest program that repeats the error:

#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;
}

Thanks for your help!


Solution

  • Your for loop breaks after i == N-2, but it should break before. The condition in your for loop should be i<N-2 instead of i<=N-2.

    So you try to access memory, which is out of bounds. This leads to undefined behaviour, so anything can happen, including a segmentation fault, a free run time error or nothing.