arrayscpointersmalloc

Function with a malloc on a pointer declared in main()


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: