[英]Can someone explain why I'm getting segmentation fault 11?
這是我的代碼:
int main() {
typedef struct {
int recordCount;
char *firstName;
char *secondName;
char *id;
char *email;
}student;
student *students = malloc(sizeof(*students));
int i = 0;
while (students[i].firstName[0] != '.'){
students[i].firstName = (char *)malloc(sizeof(char*));
scanf("%s", students[i].firstName);
i++;
students = realloc(students, sizeof(students) * (i + 1));
}
}
當我通過for循環運行它時,它很有效,我很確定這只是我的while循環中的一些愚蠢行為。
malloc
返回一塊未初始化的內存。 因此, students[i].firstName
是一個未初始化的指針,您嘗試取消引用它。 讀取和取消引用未初始化的指針會調用未定義的行為,在這種情況下會表現為崩潰。
當你做了分配空間firstName
成員,您只分配sizeof(char*)
字節,它是一個指針的大小,你想讀一個字符串不一定長度。
創建一個緩沖區來讀取字符串,使其足夠大,以滿足您的需要,然后使用strdup
創建一個副本以分配給相關指針。
student *students = NULL;
int i = 0;
char str[100];
scanf("%99s", str);
while (str[0] != '.'){
students = realloc(students, sizeof(*students) * (i+1));
students[i].firstName = strdup(str);
i++;
scanf("%99s", str);
}
作為一個開始,
students[i].firstName = (char *)malloc(sizeof(char*));
為字符指針分配足夠的空間,通常為四個或八個字節。
雖然有一些名字, 將適合在(如Pax
或Bob
),大多數可能不會。
您需要為最大的名稱(和字符串終止符)分配足夠的空間,例如:
#define MAX_NAME_LEN 100
students[i].firstName = malloc(MAX_NAME_LEN + 1);
您的代碼中存在許多問題。
malloc
,實際上指定的是data type
而不是pointer type
,我相信這不是您的意圖。 如果要指定sizeof
指針類型,則指針將指向具有指針大小的內存位置。 在這種情況下,這不是你想要的。 student *students = malloc ...
students
將指向一個內存位置,該位置將在firstName
保存零值。 你需要使用malloc來實現這些目標。 由於您沒有這樣做,因此您正在解除引用無效指針(指向位置0
)的分段錯誤。 您正嘗試先訪問它,然后再使用malloc
。 如果你
student *students = malloc(sizeof(*students));
你正在分配一個指針的大小。 你想做的是相反
student *students = malloc(sizeof(students));
出於同樣的原因, students[i].firstName = (char *)malloc(sizeof(char*))
肯定沒有足夠的內存供你的名字使用,試試malloc(sizeof(char)*100)
左右。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.