【问题标题】:Printf - access violation reading location - C++Printf - 访问冲突读取位置 - C++
【发布时间】:2010-02-07 15:01:50
【问题描述】:

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

【问题讨论】:

    标签: c++ printf


    【解决方案1】:

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

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

    【讨论】:

    • 我会强调不要使用 printf 正是这种类型安全问题
    • sepp2k 的注释中有一个错字:strings 的成员函数是 c_str 而不是 cstr。否则完美答案:)
    • @victor:哎呀,确实。现已修复。
    【解决方案2】:

    C++ string 不是 printf 所期望的 %s 说明符 - 它需要一个以空字符结尾的字符数组。

    您需要将iostream 用于输出(cout &lt;&lt; ...)或将字符串转换为字符数组,例如c_str()

    【讨论】:

      【解决方案3】:

      sepp2k 给出了正确答案,但我要补充一点:如果您打开完全警告(推荐),编译器会警告您:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-12
        相关资源
        最近更新 更多