double free or corruption (out) - Dynamic Allocation in C

0
In the discipline of Data Structure in the faculty, as an exercise, was passed the implementation of an algorithm that generates the transposed matrix of a given dynamically allocated matrix. I made the implementation and the algorithm is working correctly, however, when the user inserts in the amount of rows or columns, a value above 3 (4 up), at the end of the code execution, I get the following message: double free or corruption (out)

I looked into the error but could not find the location in the code I would be generating this message in.

Follow the code:

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

int** transposta( int m, int n, int** mat ){

    int i = 0, j = 0;

    int** matrizt = (int**)(malloc(n * sizeof(int)));

    for( i = 0; i < n; i++ )
        matrizt[ i ] = (int*)(malloc( m * sizeof(int)));

    for( i = 0; i < m; i++ )
        for( j = 0; j < n; j++)
            matrizt[ j ] [ i ] = mat[ i ] [ j ];

    return matrizt;

}

void imprime(int linhas, int colunas, int** matriz){
    int i = 0, j = 0;
    for( i = 0; i < linhas; i++ ){
        for( j = 0; j < colunas; j++ ){
            printf("%d ", matriz[i][j]);
        }
        printf("\n");
    }
    printf("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
}

int main(int argc, char** argv) {

    int linhas = 0,colunas = 0;

    int i = 0, j = 0;

    printf("Informe a quantidade de linhas: ");
    scanf("%d", &linhas);

    printf("Informe a quantidade de colunas: ");
    scanf("%d", &colunas);

    int **matriz = ( int** )( malloc( linhas * sizeof( int ) ) );

    for( i = 0; i < linhas; i++ )
        matriz[ i ] = ( int* )( malloc( colunas * sizeof( int ) ) );

    for( i = 0; i < linhas; i++ )
        for( j = 0; j < colunas; j++ )
            scanf( "%d", &matriz[ i ][ j ]);


    printf("Matriz digitada:\n");
    imprime(linhas,colunas,matriz);

    int **matrizt = transposta( linhas, colunas, matriz );

    printf("Matriz transposta:\n");
    imprime(colunas, linhas, matrizt);

    for(i = 0; i < linhas; i++)
        free(matriz[i]);

    for(i = 0; i < colunas; i++)
        free(matrizt[i]);

    free(matriz);
    free(matrizt);

    return (EXIT_SUCCESS);
}
    
asked by anonymous 30.03.2018 / 19:49

1 answer

2

The error is as follows:

int **matriz = ( int** )( malloc( linhas * sizeof( int ) ) );

You would have to use sizeof (int *) instead of sizeof (int) because you are allocating an array of arrays, not an array of integers.

Similar error is committed when allocating arrayt.

This is the type of error that would go unnoticed in a 32-bit architecture (because int has the same size as a pointer) but in 64-bit most architectures kept int with 32-bit size.

    
01.04.2018 / 16:02