簡體   English   中英

將scanf與3個輸入變量一起使用時出現分段錯誤

[英]Segmentation Fault when using scanf with 3 input variables

不知道為什么我在這里遇到細分錯誤:

//I define the variables used for input

int *numberOfDonuts;
    numberOfDonuts = (int *)malloc(sizeof(int));

char *charInput;
    charInput = (char *)malloc(sizeof(char));   

int *numberOfMilkshakes;
    numberOfMilkshakes = (int *)malloc(sizeof(int));

//Then attempt to read input
scanf("%c %d %d", &*charInput, &*numberOfDonuts, &*numberOfMilkshakes);

然后我在這條線上出現了分段錯誤。 無法解決我做錯了什么嗎?

您使用分配變量的方式使事情變得過於復雜。 這應該做您想要的:

int numberOfDonuts;
char charInput;
int numberOfMilkshakes;

scanf("%c %d %d", &charInput, &numberOfDonuts, &numberOfMilkshakes);

使用intchar這樣的基本類型,您不必為它們顯式分配內存。 編譯器會為您處理。

但是,即使按照您的方式分配它們,最終的結果還是指向值的指針,而不是值本身。 鑒於scanf需要一堆指針,則無需取消引用指針,然后再次獲取其地址,這就是您要嘗試執行的操作。 以下內容也將起作用:

int *numberOfDonuts;
    numberOfDonuts = malloc(sizeof(int));

char *charInput;
    charInput = malloc(sizeof(char));   

int *numberOfMilkshakes;
    numberOfMilkshakes = malloc(sizeof(int));

scanf("%c %d %d", charInput, numberOfDonuts, numberOfMilkshakes);

據我所知,此代碼是有效的。

它可以在我的系統上編譯並按預期工作。

這是您的整個程序嗎?

您還應該注意,不需要所有這些指針。

您可以這樣寫:

int numberOfDonuts;
char charInput;
int numberOfMilkshakes;

//Then attempt to read input
scanf("%c %d %d", &charInput, &numberOfDonuts, &numberOfMilkshakes);

printf("char=%c donuts=%d milkshakes=%d\n",
        charInput, numberOfDonuts, numberOfMilkshakes);

當程序嘗試訪問無效的內存位置時,將發生分段錯誤。

由於在程序中使用malloc分配內存,因此始終最好在嘗試在該位置存儲值之前檢查是否返回了有效的內存位置。 每次在程序中使用malloc來解決錯誤時,都應包括此檢查。

例如:

int *numberOfDonuts = (int *)malloc(sizeof(int));
if(numberOfDonuts == NULL)
{
  printf("Memory allocation Failure\n");
  return;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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