malloc 和 calloc 与 std::string 之间的区别



我最近进入了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;
}

下面的代码有效。

calloc(4, sizeof(std::string));

如果我分配正常金额的 12 倍,Malloc 也可以工作。

有人可以解释这种行为吗?这与标准::字符串有关吗?

std::string* pointer = (std::string*) malloc(4 * sizeof(std::string)); 

这仅分配足以容纳 4 个字符串对象的内存。它不构造它们,并且在构造之前的任何用途都是未定义的。

编辑:至于为什么它适用于calloc:最有可能的是,std::string的默认构造函数将所有字段设置为零。可能 calloc 只是碰巧在您的系统上做与 std::string 默认构造相同的操作。相比之下,小的 malloc(( 对象可能分配了初始垃圾,因此这些对象不处于有效状态

具有足够大的malloc()效果类似于calloc().当malloc()无法重用以前分配的块(带有潜在的垃圾(时,它会从操作系统请求新块。通常操作系统会清除它交给应用程序的任何块(以避免信息泄露(,使大 malloc(( 的行为类似于 calloc((。

这不适用于所有系统和编译器这取决于编译器如何实现std::string,也取决于未定义的行为如何混淆编译器。这意味着,如果它现在适用于您的编译器,则可能无法在其他系统或较新的编译器上运行。更糟糕的是,在您编辑程序中看似不相关的代码后,它可能会停止使用编译器在您的系统上工作永远不要依赖未定义的行为

最简单的解决方案是让C++处理分配和建设,然后再处理破坏和释放。这自动完成

std::vector<std::string> str_vec(4);

如果您坚持分配和解分配自己的内存(这在 99.9% 的情况下是一个坏主意(,您应该使用new而不是malloc。与malloc()不同,使用new实际上是构造对象。

// better use std::unique_ptr<std::string[]>
// since at least it automatically
// destroys and frees the objects.
std::string* pointer = new std::string[4];
... use the pointer ...
// better to rely on std::unique_ptr to auto delete the thing.
delete [] pointer;

如果出于某种奇怪的原因,您仍然想使用 malloc(这在 99.99% 的情况下都是一个坏主意(,您必须自己构造和破坏对象:

constexpr int size = 4;
std::string* pointer = (std::string*) malloc(size * sizeof(std::string)); 
for (int i=0; i != size ;++i)
// placement new constructs the strings
new (pointer+i) std::string;
... use the pointer ....
for (int i=0; i != size ;++i)
// destruct the strings
pointer[i].~string();
free(pointer);

有人可以解释这种行为吗?

在这两种情况下,行为都是不确定的。calloc案似乎有效只是由于运气不好。

为了在分配的内存空间中使用对象,必须首先构造该对象。您从未构造过任何字符串对象。

构造动态分配的对象数组的最简单方法是使用向量:

std::vector<std::string> vec(4);

最新更新