2010-02-07 145 views
3

0xC0000005:訪問衝突讀取位置0xcccccccc。Printf - 訪問衝突讀取位置 - C++

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正在打印精細,但第二個將拋出異常,看似不管是如何傳遞的字符串值。

回答

11

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

使用字符串'c_str方法得到char* s或不使用printf。

+2

我會把在唐的重點'不使用printf這種類型的安全問題 – Grizzly 2010-02-07 17:32:47

+0

sepp2k的評論中有一個錯字:strings'成員函數是c_str而不是cstr。完美答案,否則:) – qdii 2011-11-25 10:26:47

+0

@victor:哎呀,的確如此。現在修復。 – sepp2k 2011-11-25 11:25:31

5

A C++ stringprintf對於%s說明符的期望是什麼 - 它希望以null結尾的字符數組。

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

1

sepp2k給出了正確的答案,但我會添加一個輕微的一點:如果你打開全警告(推薦),編譯器會警告你:

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