Printf - 访问冲突读取位置 - C++

Doi*_*ois 4 c++ printf

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();
}
Run Code Online (Sandbox Code Playgroud)

第一个printf打印正常,但第二个将抛出异常,看起来无论我如何传递字符串值.

sep*_*p2k 12

printf的"%s"期望一个char*参数,而不是一个std::string.因此printf会将您的字符串对象解释为指针,并尝试访问该对象的第一个sizeof(char*)字节给出的内存位置,这会导致访问冲突,因为这些字节实际上不是指针.

要么使用字符串的c_str方法来获取char*s,要么不使用printf.

  • 我会强调不要使用printf这种类型的安全问题 (2认同)

Jak*_*org 5

C++ string不是说明符所printf期望的%s- 它想要一个空终止的字符数组.

例如,您需要使用iostreamoutput(cout << ...)或将字符串转换为字符数组c_str().