Search code examples
cmemorymalloccalloc

freeing memory in C doesn't work


I have a problem when i try to free allocated memory in C.

int i,j,**redmatrix, **bluematrix, **greenmatrix;
double **weigthMatrix,fsom;
weigthMatrix = (double**) calloc(radius*2+1,sizeof(double*));
redmatrix = (int**) calloc(radius*2+1,sizeof(int*));
bluematrix = (int**) calloc(radius*2+1,sizeof(int*));
greenmatrix = (int**) calloc(radius*2+1,sizeof(int*));
if(weigthMatrix==NULL || redmatrix==NULL || bluematrix==NULL || greenmatrix==NULL){
    printf("%s\n", "Error: probleem met geheugenallocatie");
    exit(1);
}
for(i=0;i<radius*2+2;i++){
    weigthMatrix[i] = (double*) calloc(radius*2+1,sizeof(double));
    redmatrix[i] = (int*) calloc(radius*2+1,sizeof(int));
    bluematrix[i] = (int*) calloc(radius*2+1,sizeof(int));
    greenmatrix[i] = (int*) calloc(radius*2+1,sizeof(int));
    if(weigthMatrix[i]==NULL || redmatrix[i]==NULL || bluematrix[i]==NULL || greenmatrix[i]==NULL){
        printf("%s\n", "Error: probleem met geheugenallocatie");
        exit(1);
    }
}
for(i=0;i<radius*2+1;i++){
    free(weigthMatrix[i]);
    free(redmatrix[i]);
    free(bluematrix[i]);
    free(greenmatrix[i]);
}

free(redmatrix);    //MY PROGRAM CRASHES HERE
free(bluematrix);
free(greenmatrix);
free(weigthMatrix);
free_image(&copyImage);

My program crashes when i try to free the top level of my array. I don't know what i am doing wrong. I think I allocated everything right?


Solution

  • You reserve space for radius*2+1 elements

    redmatrix = (int**) calloc(radius*2+1,sizeof(int*));
    

    But then you fill and free arrays with radius*2+2 elements

    for(i=0;i<radius*2+2;i++){
        redmatrix[i] = (int*) calloc(radius*2+1,sizeof(int));
    
    for(i=0;i<radius*2+2;i++){
        free(redmatrix[i]);
        ...
    

    change to

    for(i=0;i<radius*2+1;i++){
        redmatrix[i] = (int*) calloc(radius*2+1,sizeof(int));
        ...
    
    for(i=0;i<radius*2+1;i++){
        free(redmatrix[i]);
        ...
    

    And please, don't cast malloc