I looked at many similar questions on this subject, but most seem to focus on a pointer being passed to a function as parameter instead of the pointer’s address so haven’t found my answer.
A segfault occurs at line 11. Why ?
Cheers.
void allocateMem(int **ptr)
{
int i = 0 ;
*ptr = malloc(100 * sizeof(int)) ;
if(*ptr != NULL)
{
for(i = 0 ; i < 100 ; i ++)
{
*ptr[i] = i ; //segfault
printf("%d %d\n" , i , *ptr[i]) ;
}
free(*ptr) ;
}
else
exit(0) ;
}
int main(int argc , char *argv[])
{
int *ptr = NULL ;
allocateMem(&ptr) ;
return 0 ;
}
>Solution :
This is a precedence issue.
*ptr[i] is equivalent to *(ptr[i]) when you meant (*ptr)[i]. Naturally, *(ptr[i]) might cause a segfault because the contents of the dynamically allocated array are indeterminate and then you’re dereferencing that indeterminate value.
Other suggestions for your code:
- Use braces consistently.
- Scope your loop variables as tightly as possible. I’m specifically looking at
i. - It’s unusual for a function to exit the entire program on a memory allocation failure. It’d be more usual to return a value to the caller indicating a failure, and then let that caller decide how to handle the error.
- In practice, you also probably want to assign that dynamically allocated array to a local pointer variable and test it before assigning it to
*ptr. This way, in the event of a memory allocation failure, the original memory being pointed to by*ptris still addressable.