c - Freeing realloc causing error -
i trying free memory allocated in next 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; < 4; i++) { x[i] = i; printf("x[%d] = %d\n", i, x[i]); } x = (int *) realloc(x, 4 * sizeof(int)); for(i = 0; < 8; i++) { x[i] = i; printf("x[%d] = %d\n", i, x[i]); // free(x[i]); } free(x); }
i following: libc abort error: * glibc detected ./a.out: free(): invalid next size (fast): 0x00000000014f8010 **
i tried free within lastly loop, still gives problem. going wrong?
realloc() not increment allocated memory specified amount. reallocates requested amount of bytes. if want resize array 8 integers long, you'll need to:
x = realloc(x, 8 * sizeof(int));
btw, not cast returned value of malloc() , realloc() in c:
http://c-faq.com/malloc/mallocnocast.html
c malloc realloc
No comments:
Post a Comment