gpt4 book ai didi

c++ - 将取消引用的对象分配给对象会导致段错误

转载 作者:行者123 更新时间:2023-11-30 01:50:45 33 4
gpt4 key购买 nike

我有以下简单的程序作为说明:

#include <string>
using namespace std;

int main()
{
string name;
string *my_str;

name = "foo";
my_str = (string *) malloc(sizeof(*my_str));

*my_str = name; // fault line
// my_str = new(my_str) string(name); // fix
}

代码可以编译,但在执行过程中出现段错误:

$ ./a.out
Segmentation fault (core dumped)

$ gdb -q ./a.out ./core.31114
.....
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0 __exchange_and_add_single (__mem=<optimized out>, __val=-1)
at /home/packages/gcc/4.7/w/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/ext/atomicity.h:66
66 /home/packages/gcc/4.7/w/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/ext/atomicity.h: No such file or directory.
(gdb) bt
#0 __exchange_and_add_single (__mem=<optimized out>, __val=-1)
at /home/packages/gcc/4.7/w/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/ext/atomicity.h:66
#1 __exchange_and_add_dispatch (__mem=0xfffffffffffffff8, __val=<optimized out>)
at /home/packages/gcc/4.7/w/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/ext/atomicity.h:83
#2 std::string::_Rep::_M_dispose (this=0xffffffffffffffe8, __a=...)
at /home/packages/gcc/4.7/w/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/bits/basic_string.h:242
#3 0x00007fbab7a5ff06 in _M_grab (__alloc1=..., this=<optimized out>, __alloc2=...)
at /home/packages/gcc/4.7/w/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/bits/basic_string.h:226
#4 _M_grab (__alloc2=..., __alloc1=..., this=<optimized out>)
at /home/packages/gcc/4.7/w/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/bits/basic_string.tcc:244
#5 std::string::assign (this=0x99a040, __str=...) at /home/packages/gcc/4.7/w/gcc-4.7-4.7.2/build/x86_64-linux-gnu/libstdc++-v3/include/bits/basic_string.tcc:251
#6 0x00000000004008b3 in main () at ./strassign.cc:12

我知道问题的解决方法(用字符串“fix”注释的行)而且我也知道我应该首先使用 new。这是一个虚构的例子。我在调试一大段代码时遇到了这个问题,我(目前)没有兴趣检查所有 malloc 并将其替换为新的。

我只是想深入了解(基本上是对 bt 的解释)为什么分配段会出错。我在想对象 *my_str 的字符串复制赋值运算符将被调用,一切都应该成功。但根据结果,我想不会。任何见解将不胜感激。

谢谢,艾哈迈德。

最佳答案

my_str = (string *) malloc(sizeof(*my_str));

这会在堆上(而不是在 C++ 自由存储区)为 string 分配空间。

做的是初始化内存。
因此,虽然我们现在有足够的空间容纳 string,但我们没有 string

你的修复

my_str = new(my_str) string(name);
// Should cast the pointer-argument to `void*` before giving it to `new`.
// Otherwise, some other custom overload of `operator new` might match better.

使用 placement-new-expression 调用构造函数,并建立对象不变量(从而开始 string-objects 生命周期)。

顺便说一句:constexpr void* operator new(size_t, void*) 被定义为只返回它的第二个参数,所以只有 new 表达式的第二部分,即 ctor 调用,有任何效果。

关于c++ - 将取消引用的对象分配给对象会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27068428/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com