簡體   English   中英

有人可以解釋為什么我會得到分段錯誤11嗎?

[英]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*));

為字符指針分配足夠的空間通常為四個或八個字節。

雖然有一些名字, 適合在(如PaxBob ),大多數可能不會。

您需要為最大的名稱(和字符串終止符)分配足夠的空間,例如:

#define MAX_NAME_LEN 100
students[i].firstName = malloc(MAX_NAME_LEN + 1);

您的代碼中存在許多問題。

  1. 當您使用malloc ,實際上指定的是data type而不是pointer type ,我相信這不是您的意圖。 如果要指定sizeof指針類型,則指針將指向具有指針大小的內存位置。 在這種情況下,這不是你想要的。
  2. 在線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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM