Mohan Rajendran
Mohan Rajendran

Reputation: 11

Error while using free command in C

I am trying to code a function that generates N number of 3x3 matrices(Recursive Doubling algorithm). The following code produces an error.

#define N 4

#include<stdio.h>
#include<stdlib.h>

void CReduce(double*,double*,double*,double*,double*); //Cyclic reducer

int main()
{
    double *a,*b,*c,*d,*x;
    int size = N*sizeof(double);
    int i;

    a = (double*)malloc(size);
    b = (double*)malloc(size);
    c = (double*)malloc(size);
    d = (double*)malloc(size);
    x = (double*)malloc(size);

    //assign vector values-change later
    for(i=0;i<N;i++)
    {
        b[i] = 2.0;
        a[i] = c[i] = -1.0;
        d[i] = 0.0;
    }
    d[N-1] = 1.0;
    a[0] = 1.0;
    c[N-1] = 1.0;

    CReduce(a,b,c,d,x);

    //for(i=0;i<N;i++) printf("%d %lf\n",i,x[i]);

    free(a);
    free(b);
    free(c);
    free(d);
    free(x);

    return 0;
}

void CReduce(double* a,double* b,double* c,double* d,double* x)
{
    double *B,*C;
    int i;

    B = (double*)malloc(N*3*3);
    C = (double*)malloc(N*3*3);

    a[0] = 1.0;
    c[N-1] = 1.0;

    for(i=0;i<N*3*3;i++) B[i]=C[i]=0.0;

    free(B);
    free(C);
}

I have not fully finished the code but it already produces the following error when I run the code.

*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x00000000023f4100 ***

Could anyone guide me on what mistake I am doing? Thank you.

Upvotes: 1

Views: 1410

Answers (3)

Dietrich Epp
Dietrich Epp

Reputation: 213298

This is wrong.

B = malloc(N*3*3);

This is right.

B = malloc(sizeof(*B)*N*3*3);

Note that the (double *) is superfluous, it just takes up space on your screen.

The other answers have good advice, they've been downvoted but when N is small your program has no reason to use malloc. Unless you know that N is going to get big, then remove malloc from your code. Here, simpler is better.

Upvotes: 2

tchap
tchap

Reputation: 1057

I am not sure where the problem is, but do you really have to use dynamic allocation? Your N is a constant, so you can write

double a[N];
double b[N];
double c[N];
double d[N];
double x[N];

Upvotes: 0

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

I would like to add a suggestion. Take a look at your CReduce function -

B = (double*)malloc(N*3*3);
C = (double*)malloc(N*3*3);

............

free(B);
free(C);

Whenever you see memory allocation and memory release in the same function, you should consider removing dynamic allocation and use simple arrays instead which will do the same job better -

double B[N*3*3];
double C[N*3*3];

But there is a certain limitation on the array sizes depending on platforms, compilers etc. Some of them reports errors if the array length is quite large in the declaration. So if you require a really large array (like more than 100000 elements) then probably dynamic allocation will be the only way to go.

Upvotes: 0

Related Questions