Rodolfo Rodolfo - 14 days ago 11
C Question

Printing element of array twice results in Segmentation fault

I am trying to create a multidimensional array in c. For testing purposes, I am trying to print the first element of the first row. The code seems to work up to that point; however, when I try to print the element a second time, I get a segmentation fault:

#include <stdbool.h>
#include <stdio.h>

typedef struct Matrix {
bool** elem;
int length;
} Matrix;

void generateMatrix(Matrix* m);

int main() {
Matrix m = {0, 0};
generateMatrix(&m);

fprintf(stdout, "%d ", m.elem[0][0]);

fprintf(stdout, "\n");

// Comment next line if you want it to work
fprintf(stdout, "%d ", m.elem[0][0]);

return 0;
}

void generateMatrix(Matrix* m) {
const int size = 2;

bool* ptrArray[size];
bool ptr1[] = {false, false};
bool ptr2[] = {true, true};

ptrArray[0] = ptr1;
ptrArray[1] = ptr2;
m->elem = ptrArray;
m->length = size;
}


I am using the gcc on ubuntu:

$ gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609


Why is this happening?

Answer

The problem is in generateMatrix

here:

bool* ptrArray[size];
...
m->elem = ptrArray;

you're using a reference on a local variable, which lifespan is limited to the function call, but you store it in the return object.

So you get undefined behaviour.

First time it works because you're lucky but the second time, somehow the memory is overwritten (function calls often modify the stack, and local variables are often stored on the stack).

Fix: you actually have to allocate some memory:

bool* ptrArray = malloc(size*sizeof(ptrArray[0]));

that memory has a global lifespan. Cannot be collected unless you free it.

Comments