Seg fault when using multiple levels of indirection
-
26-10-2019 - |
Question
When allocating and then attempting to access an array of pointers to pointers:
void tester(char ***p)
{
int i;
char **pp;
pp = *p;
pp = calloc(10, sizeof(*pp));
for (i = 0; i < 10; i++)
printf("%d = %p\n", i, pp[i]);
*p = pp;
}
void tester_broken(char ***p)
{
int i;
*p = calloc(10, sizeof(**p));
for (i = 0; i < 10; i++)
printf("%d = %p\n", i, *p[i]);
}
int main(void)
{
char **a;
tester(&a);
tester_broken(&a);
return 0;
}
Can anyone explain why one of these works and the other seg faults?
Solution
It's a precedence problem. Try:
void tester_fixed(char ***p)
{
int i;
*p = calloc(10, sizeof(**p));
for (i = 0; i < 10; i++)
printf("%d = %p\n", i, (*p)[i]);
}
The bracket operator (array subscripting) binds tighter than the asterisk operator (dereference). The parentheses make your intent explict.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow