c++ - 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 有什么关系吗?
解决方案
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);
推荐阅读
- assembly - 用于编译成自定义机器语言的工具包
- apache-spark - 通过替换 AWS Redshift 表中的现有行来执行 Apache Spark 和合并操作
- c# - C# WPF MVVM - 如何填充 ObservableCollection 然后稍后在列表视图中加载数据?
- python - Django 命令“django-admin startmyproject”不起作用?
- matrix - CUDA:Matrix + Matrix,在主机中打印解决方案矩阵时出现分段错误
- c - 如何使用 strncat() 在运行时避免 Abort Trap 6 错误?
- c - char 和 int 上的 C 结构位域之间的不同
- ios - 为什么在 for-in 循环中遍历一系列变量会引发条件警告,但单独设置它们不会?
- python-3.x - 使用标头的 Python Amazon 抓取
- c++ - 如何将 std:fixed << setprecision(5) 的结果分配给 C++ 中的变量