2014-02-25 61 views
1
#include<stdio.h> 
#include <stdlib.h> 

struct a1 { 
    int value ; 
}; 

struct cf { 
    struct a1 *a1; 
    int val; 
}; 

main(){ 

    struct cf *cf = malloc(sizeof(struct cf)); 

    cf->a1->value = 45; 
    printf("cf->a1->value = %d \n",cf->a1->value); 

} 

當我綁定執行此C代碼我得到一個分段錯誤(核心轉儲)!爲什麼在下面的C代碼中發生分段錯誤

+4

您已經爲'cf'分配的空間,但是你有什麼理由認爲它'結構a1'指針,'a1',指向訪問內存? 'cf-> a1'是一個沒有意義的值,你不應該試圖解引用它。你需要一個介於中間的'cf-> a1 = malloc(sizeof(struct a1));'。 –

回答

3

原因是你分配cf所需的內存,但不是a1。 你必須做一些像

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

struct a1 { 
    int value ; 
}; 

struct cf { 
    struct a1 *a1; 
    int val; 
}; 

main(){ 

    struct cf *cf = malloc(sizeof(struct cf)); 
    cf->a1 = malloc(sizeof(struct a1)); 
    cf->a1->value = 45; 
    printf("cf->a1->value = %d \n",cf->a1->value); 

} 
0

你得到分段錯誤,因爲你沒有爲a1分配的內存。 您還應該將malloc從void*改爲struct cf*,並且如果一切順利,則聲明主要功能爲int main()return 0。 這是你的問題的解決方案:對於結構cf

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

struct a1 { 
    int value ; 
}; 

struct cf { 
    struct a1 *a1; 
    int val; 
}; 

int main(){ 

    struct cf *cf = (struct cf*)malloc(sizeof(struct cf)); 
    cf->a1=(struct a1*)malloc(sizeof(struct a1)); 

    cf->a1->value = 45; 
    printf("cf->a1->value = %d \n",cf->a1->value); 

} 
+0

你不會在C中投入'malloc' - [我投出malloc的結果嗎?](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – crashmstr

+0

@crashmstr如果你使用gcc,你會得到一個語法錯誤,如果你不轉換 – WileTheCoyot

+0

另一方面,你不應該得到一個C編譯器,C++語法錯誤,是的,你需要。問題被標記爲C雖然。 – crashmstr

0

malloc(sizeof(struct cf));現在你在這裏分配內存擁有成員爲指針a1 & val。指針a1指向結構類型a1,其中包含成員value。但malloc()只分配指針的內存,但它沒有爲成員分配內存,例如value。在那裏,你試圖將45寫入未知的存儲器。

分配內存的結構a1太爲,cf->a1 = malloc(sizeof(struct a1));

相關問題