我最近进入了C++,我遇到了使用malloc的问题.下面的代码不会打印出"成功"(程序崩溃,退出代码为0xC0000005),而如果我使用calloc,则一切正常.
int main(){
std::string* pointer = (std::string*) malloc(4 * sizeof(std::string));
for(int i = 0; i < 4; i++){
pointer[i] = "test";
}
std::cout << "Success" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以下代码有效.
calloc(4, sizeof(std::string));
Run Code Online (Sandbox Code Playgroud)
如果我分配正常数量的12倍,Malloc也可以工作.
有人可以解释这种行为吗?这与std :: string有关吗?