Code fails with segmentation fault

大憨熊 提交于 2019-12-12 03:54:17

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/16387890/code-fails-with-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!