【问题标题】:C++ : Bus Error: 10 when assign string passed in methodC ++:总线错误:在方法中分配字符串时为10
【发布时间】:2018-06-07 12:19:01
【问题描述】:

我正在尝试分配一个string,当我收到此错误时,它的值被传递到方法中:

Bus error: 10

我的代码:

struct user {
   string username;
   string password;
};

方法:

user *init_user(const string & username, const string & password){ 
    user *u = (user *)malloc(sizeof(user));
    if (u == NULL){
        return NULL;
    }
    u->username = username;
    u->password = password;
    return u;
 }

调用:

user *root = init_user("root", "root");

我认为错误是由

引发的
u->username = username;
u->password = password;

我使用的编译器是c++11

操作系统:MacOS

【问题讨论】:

  • 不要使用malloc() 分配具有非平凡构造函数/析构函数的任何成员(例如std::string)的类型。行为未定义。
  • @Peter 谢谢。问题已经解决了

标签: c++11 bus-error


【解决方案1】:

malloc 不调用构造函数,因此您分配的字符串无效,因此SIGBUS

在 C++ 中使用new,它会为您分配内存并调用构造函数:

user *init_user(const string & username, const string & password) { 
    user* u = new user;
    u->username = username;
    u->password = password;
    return u;
}

工厂函数应该返回一个智能指针,例如std::unique_ptr,以传达所有权转移并防止内存泄漏:

std::unique_ptr<user> init_user(const string & username, const string & password) { 
    std::unique_ptr<user> u(new user);
    u->username = username;
    u->password = password;
    return u;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多