[英]C++ : Bus Error: 10 when assign string passed in method
I am trying to assign a string
whose value is passed into the method when I got this error : 我正在尝试分配一个
string
,当我遇到此错误时,该string
的值将传递到方法中:
Bus error: 10
My code: 我的代码:
struct user {
string username;
string password;
};
The method: 方法:
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;
}
Calling: 呼叫:
user *root = init_user("root", "root");
I think the error is raised by 我认为错误是由
u->username = username;
u->password = password;
The compiler I'm using is c++11
我正在使用的编译器是
c++11
OS: MacOS
作业系统:
MacOS
malloc
does not call constructors, so that the strings you assign to are invalid, hence SIGBUS
. malloc
不调用构造函数,因此分配给您的字符串无效,因此为SIGBUS
。
In C++ use new
, it allocates memory and calls the constructor for you: 在C ++中,使用
new
,它将分配内存并为您调用构造函数:
user *init_user(const string & username, const string & password) {
user* u = new user;
u->username = username;
u->password = password;
return u;
}
The factory functions should return a smart-pointer, like std::unique_ptr
to convey the transfer of ownership and prevent memory leaks: 工厂函数应该返回一个智能指针,例如
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.