Jason M.
Jason M.

Reputation: 702

Heap corruption while freeing allocated memory in C

In an attempt to free up memory after a malloc command to prevent memory leaks, I am running into a heap corruption problem during runtime. My debug is telling me that my application is trying to write to memory after the end of the heap buffer has been reached. Here is what I have simplified to isolate my problem.

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

main(){

int i,j,n;
int temp[4];
int **a;

printf("Amount of intervals to be entered: ");
scanf("%d", &n);

//allocate memory for a 2d array of size (n x 4)
a = (int**) malloc(n*sizeof(int*));
for (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 the intervals a line at a time followed by a 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 up the allocated memory 


for (i=0;i<n;i++){
    free(a[i]);
}

free(a);




}

I'm not extremely familiar with allocating and de-allocating memory so I am at a loss as to what I should do.

Upvotes: 0

Views: 365

Answers (2)

user138645
user138645

Reputation: 782

//allocate memory for a 2d array of size (n x 4)
a = (int**) malloc(n*sizeof(int*));

if (!a){
    printf("malloc failed %d\n",__LINE__);
    exit(0);
}

for (i=0;i<n;i++){
    a[i] = (int*) malloc(4*sizeof(int));
}

-Move the malloc check after the call, before making use of "a"

-Use "n"

-Remove "math.h", "temp" and "j"

Upvotes: 0

Rafael Baptista
Rafael Baptista

Reputation: 11499

There may be other problems. But this at least is wrong:

a = (int**) malloc(n*sizeof(int*));
for (i=0;i<4;i++){                   <---- 4 should be n
    a[i] = (int*) malloc(4*sizeof(int));
}

Upvotes: 3

Related Questions