C++ 信号SEGV(分段故障)矢量外推回法
我正在使用linux(WSL)制作一个shell。 出于某种未知的原因,当我将一个结构指针(我创建的)推回到一个向量中时,它调用SIGNALSEGV 这些是有问题代码的主要类C++ 信号SEGV(分段故障)矢量外推回法,c++,segmentation-fault,singleton,stdvector,factory-method,C++,Segmentation Fault,Singleton,Stdvector,Factory Method,我正在使用linux(WSL)制作一个shell。 出于某种未知的原因,当我将一个结构指针(我创建的)推回到一个向量中时,它调用SIGNALSEGV 这些是有问题代码的主要类 class TimeoutCommand : public BuiltInCommand { public: bool background; std::string line; int pid; int duration; TimeoutCommand(const char* cm
class TimeoutCommand : public BuiltInCommand {
public:
bool background;
std::string line;
int pid;
int duration;
TimeoutCommand(const char* cmd_line); //prepare line
virtual ~TimeoutCommand() {}
void execute() override; ////set alarm + fork + add to joblist + add to timelist
};
class TimeoutList{
public:
struct TimeoutEntry {
std::string line;
int pid;
time_t start_time;
int duration;
TimeoutEntry(int pid,time_t start_time,std::string line,int duration)
:pid(pid),start_time(start_time),line(line),duration(duration)
{};
};
std::vector<TimeoutEntry*> TimeoutVec;
TimeoutList();
~TimeoutList() {
for (TimeoutEntry *entry : TimeoutVec)
delete entry;
}
void addCommand(TimeoutCommand* cmd); ////add new timeout
void timeoutCheck(); ////timout timedoutcommands
};
最后是有问题的功能:
void TimeoutList::addCommand(TimeoutCommand *cmd) {
time_t t= time(NULL);
if (t==-1){
perror("smash error: time failed");
return;
}
TimeoutEntry* entry = new TimeoutEntry(cmd->pid,t,cmd->line,cmd->duration);
**TimeoutVec.push_back(entry);**
}
是什么导致分段错误?
我现在没有看到任何wierd指针混乱或类似的事情
运行此命令将类似于:
超时3睡眠10
哪个是命令行
这是std::vector中导致SEGFULT的部分
push_back(const value_type& __x)
{
**if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage)**
{
_GLIBCXX_ASAN_ANNOTATE_GROW(1);
_Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish,
__x);
++this->_M_impl._M_finish;
_GLIBCXX_ASAN_ANNOTATE_GREW(1);
}
else
_M_realloc_insert(end(), __x);
}
**有问题的行用****标记。问题是我设置了一个指向TimeoutList实例的指针,而没有分配新的距离。为什么是
std::vector TimeoutVec代码>而不是std::vector TimeoutVec代码>?或者如果必须使用指针:std::vector TimeoutVec代码>?我想这不是一个特别的原因,只是为了语义。它之所以会产生不同,是因为您将不再需要手动动态内存管理,从而消除潜在的故障点。对于应用程序中的每个新调用
,您需要仔细管理内存。如果您只是有一个std::vector
,那么就不需要手动管理内存。那么你说你有问题的那一行就是:TimeoutVec.push_back({cmd->pid,t,cmd->line,cmd->duration})代码>,没有调用new
。可能是这样,但我在代码的其他地方做了一些类似的事情,我删除了说明中的所有内容。即使是这样,我也不认为这应该是seg fualt的原因。但是我在代码的其他地方做了一些类似的事情,我删除了描述中的所有内容我不愿意成为坏消息的持有者,但是C++并不是这样工作的。它不是看着代码说“我有x行调用new
,我有x行调用delete
,所以我没事”。请记住,有一个程序流正在进行,您不知道或不确定代码是如何流动的。这并不像计算源代码中的new
和delete
调用数那样简单。
push_back(const value_type& __x)
{
**if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage)**
{
_GLIBCXX_ASAN_ANNOTATE_GROW(1);
_Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish,
__x);
++this->_M_impl._M_finish;
_GLIBCXX_ASAN_ANNOTATE_GREW(1);
}
else
_M_realloc_insert(end(), __x);
}