Distributing 2D dynamic arrays and passing by reference in C

Can someone wiser than explain to me why the following code segment errors? There is no problem allocating memory by reference, but as soon as I try to assign something or free by reference, segfault will happen.

I am sure that I am lacking the fundamental concept of pointers and passing by reference, I hope that some light may be lost.

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

void allocateMatrix(float ***);
void fillMatrix(float ***);
void freeMatrix(float **);

int main() {
    float **matrix;

    allocateMatrix(&matrix);        // this function calls and returns OK
    fillMatrix(&matrix);            // this function will segfault
    freeMatrix(matrix);             // this function will segfault

    exit(0);
}

void allocateMatrix(float ***m) {
    int i;
    m = malloc(2*sizeof(float*));
    for (i = 0; i < 2; i++) {
        m[i] = malloc(2*sizeof(float));
    }
    return;
}

void fillMatrix(float ***m) {
    int i,j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            (*m)[i][j] = 1.0;        // SEGFAULT
        }
    }
    return;
}

void freeMatrix(float **m) {
    int i; 
    for (i = 0; i < 2; i++) {
        free(m[i]);                  // SEGFAULT
    }
    free(m);
    return;
}
+5
source share
3 answers

There is one set of problems here:

void allocateMatrix(float ***m) {
    int i;
    m = malloc(2*sizeof(float*));
    for (i = 0; i < 2; i++) {
        m[i] = malloc(2*sizeof(float));
    }
    return;
}

You need to assign *mto return information to the calling code, and you will also need to highlight (*m)[i]in a loop.

void allocateMatrix(float ***m)
{
    *m = malloc(2*sizeof(float*));
    for (int i = 0; i < 2; i++)
        (*m)[i] = malloc(2*sizeof(float));
}

, , , . fillMatrix() , , * :

void fillMatrix(float **m)
{
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
            m[i][j] = 1.0;        
    }
}

freeMatrix(), :

void freeMatrix(float ***m)
{
    for (int i = 0; i < 2; i++)
        free((*m)[i]);
    free(*m);
    *m = 0;
}

:

allocateMatrix(&matrix);
fillMatrix(matrix);
freeMatrix(&matrix);   
+8

. . . .

:

    allocateMatrix  &matrix
    fillMatrix  &matrix
    freeMatrix  &matrix

void allocateMatrix  float ***m
void fillMatrix  float ***m
void freeMatrix  float ***m

    (*m)[i] = malloc(2 * sizeof(float))
    (*m)[i][j] = 1.0
    free  (*m)[i]
+3

Returning a pointer from your function is probably the best way to allocate memory:

float **allocateMatrix() {
    int i;
    float **m;

    m = malloc(2*sizeof(float *));
    for (i = 0; i < 2; i++) {
        m[i] = malloc(2*sizeof(float));
    }

    return m;
}

int main() {
    float **m;

    m = allocateMatrix();

    /* do other things 
       fillMatrix(matrix);
       freeMatrix(&matrix);
    */
}
0
source

All Articles