c++ - 段。由指向结构指针的 vector 的指针引起的退出错误

标签 c++ pointers segmentation-fault c++14

在延迟这个问题和调试几天后,我发现如果我的下面的代码在从 union (以及所有提到这个 vector 的代码)中删除 vector 之后运行,seg .故障消失。

#include <string>
#include <vector>
#include <functional>

struct Task
{
  std::string Name;

  std::vector<Task*> *Subtasks;
  std::function<void(std::string const &)> Job;

  Task() {}
  Task(std::string const &arg_0) { Name = arg_0; }
  Task(std::string const &arg_0, std::vector<Task*> *arg_1) { Name = arg_0; Subtasks = arg_1; }
  Task(std::string const &arg_0, std::function<void(std::string const &)> arg_1)
  { Name = arg_0; Job = arg_1; }

  ~Task() { for (auto tItem : *Subtasks) { delete tItem; } }
};

class Console
{
private:
  std::vector<Task*> Routine;

public:
  ~Console() { for (auto tItem : Routine) { delete tItem; } } //I thought that this is not needed but Valgrind thinks otherwise, strangely the deconstructors of the Tasks are not called, I guess.

  void add(Task *arg_0) { Routine.push_back(arg_0); }

  void foo()
  {
    Task *tTask = new Task();
    //Task *tTask = new Task("Name");
    //Task *tTask = new Task("Name", [this](std::string const &arg_0){ ; });
   //Seg. fault still remains.
    add(tTask);
  }
};

int main()
{
    Console _Console;
    _Console.foo();
}

For quick online IDE code test


这应该是另一个问题,但我认为它太简单了。 我以前听说过,如果在 union 中使用了一个非平凡的值,则应该注意是否切换了值,该怎么做,如果我不打算更改任何值,是否有必要在运行时?

编辑1

删除了 vector 和 std::function 的 union

编辑2

赛格。故障很可能是由解构器~Task();引起的。

最佳答案

如果这个构造函数被调用:

Task(std::string const &arg_0, std::function<void(std::string const &)> arg_1)
{ Name = arg_0; Job = arg_1; }

然后当调用析构函数时肯定会崩溃,因为 Subtasks 没有初始化。

~Task() { for (auto tItem : *Subtasks) { delete tItem; } }

修复:

Task(std::string const &arg_0, std::function<void(std::string const &)> arg_1)
{ Name = arg_0; Job = arg_1; Subtasks = nullptr;}

~Task() { if (Subtasks!=nullptr) for (auto tItem : *Subtasks) { delete tItem; } }

和(感谢评论)像这样收集/替换并修复所有其他构造函数:

 Task(std::string const &arg_0 = "", std::vector<Task*> *arg_1 = nullptr) { Name = arg_0; Subtasks = arg_1; }

经过一些讨论,问题的代码似乎存在设计缺陷:删除 vector 的内容是危险的,因为指针可能仍在被其他客户端使用,或者甚至可能没有分配,但是只引用局部变量。 为什么 Subtasks 首先是一个指针?为什么不删除呢?

关于c++ - 段。由指向结构指针的 vector 的指针引起的退出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39377977/

相关文章:

c - 如何在不将其作为 C 函数的返回值的情况下修改 int 指针?

c - malloc 二维数组时出现问题

c++ - 写入共享内存时出现段错误

无法在我的 pop 函数中释放/取消分配空间?

c++ - 为什么在使用 MinGW 添加 ltalloc 时会出现段错误

c++ - std::function.target 返回 null

c++ - 如何使用 c && 将应用程序输出重定向到 Qt 中的 textEdit 来调用 c++ 函数

c++ - 如何为 C++ 代码使用 cppcheck 的内联抑制过滤器选项?

c++ - 初始化 union

C++ 引用/指针