Search code examples
cmallocrealloc

Freeing realloc causing error


I am trying to free my memory allocated in the following program:

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

void main(int argc, char** argv) {
  int* x = (int *) malloc(4 * sizeof(int));
  int i;

  for(i = 0; i < 4; i++) {
   x[i] = i;
   printf("X[%d] = %d\n", i, x[i]);
  }

   x = (int *) realloc(x, 4 * sizeof(int));

   for(i = 0; i < 8; i++) {
     x[i] = i;
     printf("X[%d] = %d\n", i, x[i]);
//   free(x[i]);
   }

  free(x);
}

I get the following: libC abort error: * glibc detected ./a.out: free(): invalid next size (fast): 0x00000000014f8010 **

i tried to free inside the last loop, but that still gives a problem. Where am I going wrong?


Solution

  • realloc() does not increase the allocated memory by the specified amount. It reallocates exactly the requested amount of bytes. So if you want to resize your array to be 8 integers long, you'll need to:

    x = realloc(x, 8 * sizeof(int));
    

    Btw, do not cast the returned value of malloc() and realloc() in C:

    http://c-faq.com/malloc/mallocnocast.html