Search code examples
cmemory-corruptiondouble-free

Why does this C code yields a double free or corruption?


Why is this code for the computation of the inner product of two vectors yields a double free or corruption error, when compiled with:

ejspeiro@Eduardo-Alienware-14:~/Dropbox/HPC-Practices$ gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4

The code comes from this reference.

// Computation of the inner product of vectors aa and bb.

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

int main() {

  size_t nn = 100000000;
  size_t total_mem_array = nn*sizeof(double);

  double *aa;
  double *bb;
  double ss = 0.0;

  aa = (double *) malloc(total_mem_array);
  bb = (double *) malloc(total_mem_array);

  int ii = 0;

  for (ii = 0; ii < nn; ++ii) {
    aa[ii] = 1.0;
    bb[ii] = 1.0;
  }

  double sum1 = 0.0;
  double sum2 = 0.0;

  for (ii = 0; ii < nn/2 - 1; ++ii) {
    sum1 += (*(aa + 0))*(*(bb + 0));
    sum2 += (*(aa + 1))*(*(bb + 1));
    aa += 2;
    bb += 2;
  }
  ss = sum1 + sum2;

  free(aa);
  free(bb);

  return 0;
}

Solution

  • The error is caused because the value passed to free() is not the same value returned by malloc(), as you increment aa and bb.

    To correct it you could, for example, define two additional pointer variables that are used only for memory management, i.e. allocation and deallocation. Once memory is acquired by them, assign it to aa and bb.