1

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!

braX
  • 11,506
  • 5
  • 20
  • 33
Javier Garcia
  • 539
  • 1
  • 4
  • 15
  • 4
    the condition in your for loop should be `i – mch Apr 22 '15 at 13:57
  • 3
    @mch - good catch; your comment should be an answer. – Carl Norum Apr 22 '15 at 13:58
  • Thanks @mch! That solves the problem. So, what I'm trying to do with my erroneous code is to store N-1 mpf_t's in a space that can only handle N-2 mpf_t's. I thought that this would've produced a segmentation fault, or something like that. – Javier Garcia Apr 22 '15 at 14:03

1 Answers1

2

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.

mch
  • 9,424
  • 2
  • 28
  • 42