'munmap_chunk(): invalid pointer, memcpy() modifies source pointer?

I am writing a program that extracts a submatrix block (half of source) from a bigger matrix.

The idea is to loop on rows, and copy each row from source matrix with memcpy.

Only problem is when I do a free() on the initial source matrix I get munmap_chunk() error. I know this happens when I free a pointer that was not allocated by malloc. But this makes no sense here! my mat[i] that I try to free was allocated by malloc. And it was only used as source in memcpy. Is memcpy modifying the source?!

My code looks like this:

void print(int ** data, size_t m,size_t n)
{

    int i,j;
    
    printf("\n");
    for(i=0;i<m;i++)
    {    for(j=0;j<n;j++)
        {
            printf("%d ",data[i][j]);
        }
    printf("\n");
    }
}


void init(int** tab, int n,int m ){
    const int size_s = 8;
    int mat[size_s][size_s] = {
        { 1, 2, 3, 4, 5, 6, 7, 8},
        { 9,10,11,12,13,14,15,16},
        {17,18,19,20,21,22,23,24},
        {25,26,27,28,29,30,31,32},
        {33,34,35,36,37,38,39,40},
        {41,42,43,44,45,46,47,48},
        {49,50,51,52,53,54,55,56},
        {57,58,59,60,61,62,63,64}
    };

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            tab[i][j]= mat[i][j];
        }
    }
}

--Main function

int main (void){
    const int n = 8;
    int sub_mtrx_size = n/2;
    int ** mat =  malloc(sizeof(int*) * n);
    int ** submat =  malloc(sizeof(int*) * n/2);
    for (int k = 0; k < n; k++) {
        mat[k] =  malloc(sizeof(int) * n);
        if ( k < n/2){
            submat[k] =  malloc(sizeof(int) * (n/2));
        }
        
    }
    init (mat,n,n);
    // start problem: when doing memcpy this issue happen, commenting this leads to no errors
    memcpy( submat[0] , mat[0], sub_mtrx_size* sizeof(&submat) );
    memcpy( submat[1] , mat[1], sub_mtrx_size* sizeof(&submat) );
    memcpy( submat[2] , mat[2], sub_mtrx_size* sizeof(&submat) );
    memcpy( submat[3] , mat[3], sub_mtrx_size* sizeof(&submat) );
    // end problem 
    
    print(submat,4,4);

      for (int i = 0; i < n; i++)
    {
        // free(mat[i]); // this line creates the problem !
        if ( i < n/2){
            free(submat[i]);
        }
    }
    free (mat);
    free (submat);
    return 0;
}

How do I avoid this issue and free the memory properly?

Thanks



Solution 1:[1]

Calls of memcpy like this

memcpy( submat[0] , mat[0], sub_mtrx_size* sizeof(&submat) );

is incorrect. The expression sizeof(&submat) gives the size of a pointer of the type int ***.

You need to write

memcpy( submat[0] , mat[0], sub_mtrx_size* sizeof( int) );

or

memcpy( submat[0] , mat[0], sub_mtrx_size * sizeof( *submat[0] ) );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vlad from Moscow