Problems with dynamic array allocation

3

I'm trying to dynamically allocate an array, however I'm having some problems in runtime and I'm also getting a warning from GCC in < in> compile 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) ???

Compiling and executing 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 is wrong with the m_malloc and m_free functions? In m_free I will release the columns first and then the rows. Should not it work that way?

Question saved for future references

    
asked by anonymous 27.12.2018 / 16:10

1 answer

3

To resolve the warning compile change its function to be done this way:

int **m_malloc(size_t rows, size_t columns){
    int **mat = malloc(sizeof(int*)*rows);
    for(size_t i=0; i<rows; i++){
        mat[i]=malloc(sizeof(int)*columns);
    }
    return mat;
}

This should be done because m_malloc() is receiving a variable of type *int[] but variable is not yet created, just the pointer to it ( int **matrix; ).

As it is returned in the function the call should be changed to this:

matrix=m_malloc(rows, columns);
    
27.12.2018 / 16:25