Liz Salander
Liz Salander

Reputation: 321

Errors if free() is called after malloc() in C++

I allocate space for array I call test, which will have (2*n + 1) elements of type double. I populate the array, and finally I free() it. But if I use free(), I get an error: "double free or corruption(out): 0x0000000000000f1dc20". If I comment free(), the code runs. I cannot spot the issue.

using namespace std;
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

long    n=512; //grid size
double *test;

int main() 
{
    test = (double*) malloc(sizeof(double) * (2*n+1));

    for (long j=-n;j<=n;j++)
    {
        test[j] = double(j);
    }

    free(test); //<--- gives me error if I use this
    return 0;
 }

Upvotes: 0

Views: 571

Answers (1)

ThingyWotsit
ThingyWotsit

Reputation: 368

No, that will just not do.

You allocate enough space for an 2n array of doubles, but C defines the array indices ranging [0..2n-1]. You cannot arbitrarily decide to access the elements with [-n..+n]. As already described in comments, it's Undefined Behavior.

If you need to do what you seem to be doing, you will have to use an offset for all the accesses, eg:

test[j+n] = double(j);

You then stand a much better chance of not destroying your heap structure and so getting annoying error messages from your C and/or OS memory manager.

Upvotes: 3

Related Questions