2013-05-05 127 views
0

我的代码中出现分段故障失败。 我已经将代码缩小到这个简化版本。我删除了明显的malloc检查,因为malloc中没有失败。 我在尝试访问do_something中的[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) 
+3

请缩进您的代码。 – Elazar 2013-05-05 18:49:01

+0

使用调试器。 – 2013-05-05 18:50:38

+0

请检查编辑第一行,添加一些措辞。 – 2013-05-05 18:53:53

回答

4

初始化xyzmainNULL,如

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

否则,*xyz可能不是NULL和give_mem_and_do不会为分配内存需要指针。

+0

谢谢你解决问题。 – JRK 2013-05-05 18:59:32

相关问题