0

我的代码中出现分段错误失败。我已将代码缩小到这个简化版本。我已经删除了明显的 malloc 检查,因为 malloc 没有失败。当我尝试在 do_something 中访问 a[0] 时出现错误,但是当我尝试在 give_mem_and_do 中访问相同的内容时它不会失败。我无法理解原因。我正在传递已在堆上分配的位置的地址。那么为什么它在访问这个位置时会失败。

    #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;
    }

以下是此代码的输出

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

1 回答 1

4

初始化xyzmainNULL

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

否则,*xyz可能不是 NULL 并且give_mem_and_do不会为所需的指针分配内存。

于 2013-05-05T18:55:42.467 回答