簡體   English   中英

UndefinedBehaviorSanitiser 問題 - CS50 Vigenere

[英]UndefinedBehaviorSanitiser Issue - CS50 Vigenere

當我使用任何通過初始篩選的參數運行程序時,我正在研究 Vigenere (CS50) 並不斷收到“UndefinedBehaviorSanitiser SEGV on Unknown Address”。

我已閱讀有關此問題的信息,但找不到解決方案。 我盡可能地減少了我的代碼,發現即使我做了這部分也會出現問題。 問題出在哪里? 太感謝了。

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

//int shift(char c);

int main(int argc, string argv[])
{
    if (argc != 2)
        {
        printf("Usage: ./vigenere keyword");
        return 1;
        }
    else
        {
        for (int i = 0; i < strlen(argv[1]); i++)
            {
            if (!isalpha(argv[1]))
            {
                printf("Usage: ./vigenere keyword");
                return 1;
            }
            else
            {
                printf("All good!");
                return 1;
            }
         }
    }
}

修復確實是

if (!isalpha((unsigned char)argv[1][i]))

isalpha函數/宏只需要一個 integer,它必須具有單個字符的值作為unsigned char 但是argv[1]是指向多個字符的指針!

現在,作為一個額外的復雜因素, isalpha通常被實現為宏,並且通常進行編碼,以便編譯器不會對錯誤類型的參數產生任何診斷。 這是不幸的,但是當你在 C 中編程時,你只需要知道這些。

也需要將char轉換為unsigned char - 如果不需要,那么任何擴展字符(例如ä )將在char已簽名的平台上調用未定義的行為 -它們位於 x86 處理器上 - 因為該值將為負數,但是isalpha只需要一個EOF或小於或等於UCHAR_MAX的非負數。

暫無
暫無

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

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