JRK
JRK

Reputation: 182

Code fails with segmentation fault

I am getting a segmentation fault failure in my code. I have narrowed down the code to this simplified version. I have removed the obvious malloc checks as there was no failure in malloc . I am getting an error when I try to access a[0] in do_something but when I try to access the same in the give_mem_and_do it doesnt fail. I am not able to comprehend the reason . I am passing the address of a location that is already allocated on the heap. So why should it in fail in accessing this location.

    #include <stdio.h>
    #include <stdlib.h>

    struct abc
    {
    int *a;
    int b;
    };

    typedef struct abc thing;

    int do_something( thing ** xyz, int a)
    {
    printf ("Entering do something \n");
    (*xyz)->a[0] = a;
    return 0; 
    }

    int give_mem_and_do (thing ** xyz, int *a)
    {
    int rc;
    printf ("\n Entered function give_mem_and_do \n");
    if (*xyz == NULL)
    {
    *xyz = (thing *)malloc ( sizeof (thing) );
    (*xyz)->a = (int *) malloc (sizeof (int)*100);
    }
    printf (" Calling do_something \n");
    rc = do_something (xyz, *a);
    return 0; 
    }

    int main ()
    {
    thing * xyz;
    int abc = 1000;

    give_mem_and_do (&xyz,&abc);

    #include <stdio.h>
    #include <stdlib.h>

    struct abc
    {
    int *a;
    int b;
    };

    typedef struct abc thing;

    int do_something( thing ** xyz, int a)
    {
    printf ("Entering do something \n");
    (*xyz)->a[0] = a;
    return 0; 
    }

    int give_mem_and_do (thing ** xyz, int *a)
    {
    int rc;
    printf ("\n Entered function give_mem_and_do \n");
    if (*xyz == NULL)
    {
    *xyz = (thing *)malloc ( sizeof (thing) );
    (*xyz)->a = (int *) malloc (sizeof (int)*100);
    }
    printf (" Calling do_something \n");
    rc = do_something (xyz, *a);
    return 0; 
    }

    int main ()
    {
    thing * xyz;
    int abc = 1000;

    give_mem_and_do (&xyz,&abc);

    return 0;
    }

Following is the output of this code

    Entered function give_mem_and_do 
    Calling do_something 
    Entering do something 
    Segmentation fault (core dumped)

Upvotes: 0

Views: 105

Answers (1)

Rohan
Rohan

Reputation: 53386

Initialize xyz in main to NULL, as

int main ()
{
    thing * xyz = NULL;
...
}

Otherwise, *xyz may not be NULL andgive_mem_and_do will not allocate memory for required pointers.

Upvotes: 4

Related Questions