首页 > 解决方案 > 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 有什么关系吗?

标签: c++mallocstdstringcalloc

解决方案


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(), usingnew实际上构造了对象。

// 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);

推荐阅读