我编写了下面的示例程序,但它会因为段错误而崩溃。问题似乎出在在结构体中使用malloc
和std::string
上。
#include <iostream>
#include <string>
#include <cstdlib>
struct example {
std::string data;
};
int main() {
example *ex = (example *)malloc(sizeof(*ex));
ex->data = "hello world";
std::cout << ex->data << std::endl;
}
我无法弄清楚如何使它工作,不知道是否有可能同时使用 malloc()
和 std::string
。谢谢,Boda Cydo。
new(std::nothrow) example
来使new
返回空指针而不是抛出异常。你必须包含头文件<new>
才能使用std::nothrow
常量。 - AnT stands with Russianew
在失败时返回一个空指针,请使用new(nothrow) example
。但是,你应该使用try
/catch
来捕获任何抛出的异常。(例如,std::string
赋值也可能会因为无法分配内存而抛出异常。) - jamesdlin