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

Asked

Viewed 1,626 times

0

In the discipline of Data Structure in college, as an exercise, the implementation of an algorithm that manages the transposed matrix of a given dynamically allocated matrix was passed. I made the implementation and the algorithm is working correctly, however, when the user inserts in the number 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 searched about the error but did not find the location in the code that would be generating this message.

Follows 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);
}

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), as it is allocating a matrix of matrices, not an array of integers.

Similar error is made when allocating matrizt.

It’s the kind of error that would go unnoticed on a 32-bit architecture (because int is the same size as a pointer) but on 64-bit most architectures kept int 32-bit size.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.