簡體   English   中英

Printf - 訪問沖突讀取位置 - C ++

[英]Printf - access violation reading location - C++

0xC0000005:訪問沖突讀取位置0xcccccccc。

printf拋出此異常。

我不知道為什么會發生這種情況......這些字符串變量中有值。 我使用printf錯了嗎?

救命! (請看開關盒)

string header;
string body;
string key;

if (!contactList.isEmpty()) {

    cout << "Enter contact's name: ";
    getline(cin, key);
    Contact * tempContact = contactList.get(key);
    if (tempContact != NULL) {
        string name = tempContact->getName();
        string number = tempContact->getNumber();
        string email = tempContact->getEmail();
        string address = tempContact->getAddress();

        //I've just put this here just to test if the variables are being initialized
        cout << name + " " + number + " " + email + " " + address << endl;

        switch (type) {
            case 1:
                printf("%-15s %-10s %-15s %-15s\n", "Name", "Number", "Email", "Address");
                printf("%-15s %-10s %-15s %-15s\n", name, number, email, address);
                break;
            case 2:
                printf("%-15s %-10s\n", "Name", "Number");
                printf("%-15s %-10s\n", name, number);
                break;
            case 3:
                printf("%-15s %-15s\n", "Name", "Email");
                printf("%-15s %-15s\n", name, email);
                break;
            case 4:
                printf("%-15s %-15s\n", "Name", "Address");
                printf("%-15s %-15s\n", name, address);
                break;
            default:
                printf("%-15s %-10s %-15s %-15s\n", "Name", "Number", "Email", "Address");
                printf("%-15s %-10s %-15s %-15s\n", name, number, email, address);
        }

    } else {
        cout << "\"" + key + "\" not found.\n" << endl;
        wait();
    }

} else {        
    cout << "Contact list is empty.\n" << endl;
    wait();
}

第一個printf打印正常,但第二個將拋出異常,看起來無論我如何傳遞字符串值。

printf的“%s”期望char*作為參數,而不是std::string 因此printf會將您的字符串對象解釋為指針,並嘗試訪問該對象的第一個sizeof(char*)字節給出的內存位置,這會導致訪問沖突,因為這些字節實際上不是指針。

要么使用字符串的c_str方法來獲取char* s,要么不使用printf。

C ++ string不是printf%s說明符所期望%s - 它想要一個空終止的字符數組。

您需要使用iostream作為輸出( cout << ... )或將字符串轉換為字符數組,例如c_str()

sepp2k給出了正確的答案,但我要補充一點:如果你打開完全警告(推薦),編譯器會警告你:

a.cc:8: warning: format ‘%s’ expects type ‘char*’, but argument 2 has type ‘int’

暫無
暫無

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

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