3
I’m trying to dynamically allocate a matrix, but I’m having some problems with running time and I’m also getting a Warning of GCC in the compilation time.
Follow the code below for a better analysis of the problem:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int **m_malloc(int *mat[], size_t rows, size_t columns){
    mat=malloc(sizeof(int)*rows);
    for(size_t i=0; i<rows; i++){
        mat[i]=malloc(sizeof(int)*columns);
    }
    return mat;
}
void m_show(int *mat[], size_t rows, size_t columns){
    printf("\n");
    for(size_t i=0; i<rows; i++){
        for(size_t j=0; j<columns; j++){
            printf("[%d] ", mat[i][j]);
        }
        printf("\n");
    }
}
void m_fill(int *mat[], size_t rows, size_t columns){
    int value;
    srand(time(NULL));
    for(size_t i=0; i<rows; i++){
        for(size_t j=0; j<columns; j++){
            value=(int)rand()%100;
            mat[i][j]=value;
        }
    }
}
void m_free(int *mat[], size_t columns){
    for(size_t i=0; i<columns; i++){
        free(mat[i]);
    }
    free(mat);
}
int main(void){
    int **matrix;
    size_t rows, columns;
    printf("ROWS >");
    scanf("%ld", &rows);
    printf("COLUMNS >");
    scanf("%ld", &columns);
    matrix=m_malloc(matrix, rows, columns);
    m_fill(matrix, rows, columns);
    m_show(matrix, rows, columns);
    m_free(matrix, columns);
    return 0;
}
//matriz == matrix (in English) ???
Compilation and execution of the above code:
zherkezhi@zherkezhi :~/Documents/C$ gcc -Wall matrix.c -o app
matrix.c: In function ‘main’:
matrix.c:70:11: warning: ‘matrix’ is used uninitialized in this 
function [-Wuninitialized]
 matrix=m_malloc(matrix, rows, columns);
 ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
zherkezhi@zherkezhi :~/Documents/C$ ./app
ROWS >3
COLUMNS >3
[99] [68] [99] 
[16] [5] [50] 
[8] [62] [12]
zherkezhi@zherkezhi :~/Documents/C$ ./app
ROWS >4
COLUMNS >5
[95] [7] [34] [2] [68] 
[59] [19] [1] [37] [82] 
[25] [43] [16] [4] [50] 
[38] [46] [68] [4] [52]
double free or corruption (out)
Aborted (core dumped)
zherkezhi@zherkezhi :~/Documents/C$
What’s wrong with the job m_malloc and m_free? In m_free I released the columns first and then the rows. It shouldn’t work that way?
I was able to solve the Warning problem using the solution described by @Pilati abaxio. However that runtime error persists.
– Zherkezhi