2013-05-05 128 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

相關問題