[英]why Segmentation fault occurs in the following C code
#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代碼時,我遇到了分段錯誤(核心轉儲)!
原因是你為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);
}
由於尚未為a1
分配內存,因此會出現分段錯誤。 您還應該將malloc從void*
為struct cf*
,並將main函數聲明為int main()
,如果一切順利,則return 0
。 這是您的問題的解決方案:
#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);
}
malloc(sizeof(struct cf));
這里你為struct cf
分配內存,它有成員作為指針a1
和val
。 指針a1
指向結構類型a1
,其中包含成員value
。 但是malloc()
只為指針分配內存,但是它沒有為它擁有的成員(即value
分配內存。 那里你試圖寫45
到一個未知的記憶。
也為struct a1
分配內存, cf->a1 = malloc(sizeof(struct a1));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.