printf - 访问冲突读取位置 - C++ [英] Printf - access violation reading location - C++

查看:77
本文介绍了printf - 访问冲突读取位置 - C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

0xC0000005:访问冲突读取位置 0xcccccccc.

0xC0000005: Access violation reading location 0xcccccccc.

printf 正在抛出这个异常.

printf is throwing this exception.

我不知道为什么会发生这种情况...这些字符串变量中有值.我使用 printf 错了吗?

I don't know why this is happening... There are values in those string variables. Am I using printf wrong?

帮助!(请看开关盒)

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 打印正常,但第二个会抛出异常,似乎不管我如何传入字符串值.

The first printf is printing fine but the second one will throw the exception, seemingly regardless of how I pass the string value in.

推荐答案

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

printf's "%s" expects a char* as an argument, not a std::string. So printf will interpret your string objects as pointers and try to access the memory location given by the object's first sizeof(char*) bytes, which leads to an access violation because those bytes aren't really a pointer.

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

Either use the strings' c_str method to get char*s or don't use printf.

这篇关于printf - 访问冲突读取位置 - C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆