Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 *ptr is still addressable.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading