执行新向量时出现段错误

发布于 2024-10-07 03:46:36 字数 665 浏览 3 评论 0原文

以下代码在最后一行出现段错误:

   HookAct *act = new HookAct;
    act->hkAct = HookAct::PRINT;
    act->params = new vector<string>;

Valgrind 告诉我:

==15551== Process terminating with default action of signal 11 (SIGSEGV)
==15551== Access not within mapped region at address 0x0
==15551== at 0x5927026: std::string::assign(char const*, unsigned long) (in /usr/lib/libstdc++.so.6.0.10)
==15551== by 0x725424A: test (test.cpp:10)

有谁知道它为什么这样做?

仅供参考,这是 HookAct 的[当前、临时]定义:

struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> *params;
};

The following code gets a seg fault on the last line:

   HookAct *act = new HookAct;
    act->hkAct = HookAct::PRINT;
    act->params = new vector<string>;

Valgrind tells me:

==15551== Process terminating with default action of signal 11 (SIGSEGV)
==15551== Access not within mapped region at address 0x0
==15551== at 0x5927026: std::string::assign(char const*, unsigned long) (in /usr/lib/libstdc++.so.6.0.10)
==15551== by 0x725424A: test (test.cpp:10)

Does anyone have any idea why it is doing this?

FYI, here's the [current, temporary] definition of HookAct:

struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> *params;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自此以后,行同陌路 2024-10-14 03:46:36

正如Brian所说,错误消息指向str: :stringNULL 初始化,这是禁止的。然而,您的代码看起来像是由来自 Java 或 C# 的人编写的,并且习惯于盲目地new一切。然而,在 C++ 中,自动存储是首选。

如果将代码更改为此,

struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> params;
    HookAct() : hAct(HookAct::PRINT), params() {}
};

则不再需要手动动态内存管理:

HookAct hookAct;

As Brian said, the error message points at str::string being initialized with NULL, which is forbidden. However, your code looks like written by someone who comes from Java or C# and is used to mindlessly new everything. In C++, however, automatic storage is preferred.

If you change your code to this

struct HookAct {
    enum {
        PRINT
    } hkAct;
    vector<string> params;
    HookAct() : hAct(HookAct::PRINT), params() {}
};

no manual dynamic memory managing is necessary anymore:

HookAct hookAct;
故事还在继续 2024-10-14 03:46:36

你粘贴的代码没问题。

我认为您的问题可能是将 NULL 字符串添加到向量 act->params 中。

The code you pasted is fine.

I think your problem is probably adding a NULL string to the vector act->params.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文