【发布时间】:2014-07-01 08:17:50
【问题描述】:
在访问 std::string 类型的结构成员时,弹出错误 Bus Error: 10。代码如下。
#include <iostream>
#include <string>
struct KeyValuePair {
std::string key;
std::string value;
};
struct KeyValuePair *temp = (struct KeyValuePair *) malloc(sizeof(struct KeyValuePair));
int main(void) {
temp->value = "|";
temp->value += "someval|";
std::cout << temp->value << std::endl;
return 0;
}
在代码上运行 gdb 会在 temp->value = "|" 行显示以下内容。
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff8d99e524
0x00007fff898dc7ca in std::string::_M_mutate ()
从上面的消息中,我了解到我的代码正在尝试访问无效/未经授权的内存区域。
我的问题:虽然我已经使用 malloc 来获取全局变量 temp 的内存区域,但为什么我无法访问它。我错过了什么。请帮忙。
【问题讨论】:
标签: c++ c++11 malloc stdstring