Heap corruption while freeing allocated memory in C -
in attempt free memory after malloc command prevent memory leaks, running heap corruption problem during runtime. debug telling me application trying write memory after end of heap buffer has been reached. here have simplified isolate problem.
#include <stdio.h> #include <stdlib.h> #include <math.h> main(){ int i,j,n; int temp[4]; int **a; printf("amount of intervals entered: "); scanf("%d", &n); //allocate memory 2d array of size (n x 4) = (int**) malloc(n*sizeof(int*)); (i=0;i<4;i++){ a[i] = (int*) malloc(4*sizeof(int)); } if (!a){ printf("malloc failed %d\n",__line__); exit(0); } printf("please enter intervals line @ time followed return: \n"); for(i=0;i<n;i++){ scanf("%d %d %d %d",&a[i][0], &a[i][1], &a[i][2], &a[i][3]); } for(i=0;i<n;i++){ printf("%d, %d, %d, %d\n", a[i][0], a[i][1], a[i][2], a[i][3]); } // free allocated memory (i=0;i<n;i++){ free(a[i]); } free(a); }
i'm not extremely familiar allocating , de-allocating memory @ loss should do.
there may other problems. @ least wrong:
a = (int**) malloc(n*sizeof(int*)); (i=0;i<4;i++){ <---- 4 should n a[i] = (int*) malloc(4*sizeof(int)); }
Comments
Post a Comment