Eli Sadoff Eli Sadoff - 8 days ago 6
C Question

Double pointer doesn't get malloc'd in function

So I'm working in C and I have an

int **
inside of one function that is modified within another function. I was getting a SegFault when I was running this problem so I decided to debug it with
gdb
. What I found was that memory was never allocated to this array. My functions are like this

void declarer()
{
int ** a;
alocator(a, 4, 5);
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
printf("%d\n", a[i][j]);
}

void alocator(int ** a, int b, int c)
{
a = (int **)malloc(sizeof(int *) * b);
for (int i = 0; i < b; i++) {
a[i] = (int *)malloc(sizeof(int) * c);
for (int j = 0; j < c; j++)
a[i][j] = j;
}
}


When I run
gdb
with a breakpoint after the line
alocator(a, 4, 5)
(before the program segfaults), and I write
p a
, I get
$1 = (int **) 0x0
which shows that
a
is at address
0x0
and has no memory allocated for it. Why did
alocator
not allocate memory to it, and how can I get
alocator
to allocate memory to
a
?

Answer

Because you are passing **a by value, you have to pass it as pointer. So use a triple pointer:

void declarer()
{
    int **a;
    alocator(&a, 4, 5);
    ...
}

void alocator(int ***a, int b, int c)
{
    *a = (int **)malloc(sizeof(int *) * b);
    ...