簡體   English   中英

驗證用戶輸入時如何處理緩沖區錯誤

[英]How to handle buffer error while validating user input

我需要以整數形式讀取用戶輸入,以將其傳遞給其他函數。 如果我使用我的驗證(下面的代碼),則在4個錯誤的輸入后崩潰。 我不確定這是否是緩沖區錯誤。 但是我也沒有找到驗證我的輸入和處理錯誤的正確方法。 我沒有故意使用scanf(%d) ,因為我想避開CLion在使用它時給我的警告。 我希望這里有人可以向我解釋為什么在4個錯誤的輸入之后我的代碼崩潰,以及如何解決它,或者向我展示一種替代方法。

char *userInput = malloc(100);
long amountOfPlayers;
//Todo: More Validation needed, bufferoverflow
for (int i = 0; i < sizeof(userInput) / sizeof(*userInput); i++) {
    char *end;
    printf("Please enter the amount of players: ");
    scanf("%s", userInput);
    amountOfPlayers = strtol(userInput, &end, 10);
    if (end == userInput) {
        printf("wasn't a number\n");
    }
    else if (end[0] != '\0') {
        printf("trailing characters after number %ld: %s\n", amountOfPlayers, end);
    }
    else
        return init_playerList(amountOfPlayers);
}

userInput是指針,而不是數組,因此sizeof(userInput)返回指針的大小,通常為4個字節。 sizeof(*userInput)sizeof(char) ,即1 因此sizeof(userInput) / sizeof(*userInput)為4,這意味着您的for循環僅執行4次。 請參見如何查找“ sizeof”(指向數組的指針)?

有沒有需要一個for循環,只需使用while (true) 您無需對userInput的元素進行任何迭代,它只是緩沖區。

也沒有理由使用malloc()分配它,您可以簡單地聲明:

char userInput[100];

您有內存泄漏,因為您從函數返回之前從不free(userInput) 但是,如果將其聲明為數組,則沒有必要。

為了防止緩沖區溢出,您應該使用:

scanf("%100s", userInput);

sizeof(userInput) / sizeof(*userInput)不會返回元素數,因為userInput是一個指針,而不是數組。 這僅適用於純數組。 如果指針總是返回相同的值:指針的大小除以對象的大小。

int size = 100;
char *userInput = malloc(size);
if(userInput == NULL)
{
    // error handling
}

for (int i = 0; i < n; i++) {
    ....
}

是正確的。

暫無
暫無

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

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