繁体   English   中英

C ++代码抛出段。 故障

[英]C++ code throwing Seg. Fault

我有一个C ++代码,如下所示:

tryIt.h文件

class tryIt : public someOtherClass
{
public:
       bool insertI ();
private:
       CommandI* m_pInsertI;
       bool createInsertI();
}

tryIt.cpp文件

tryIt ::tryIt () : m_pInsertI(NULL)
{
    createInsertI();
}

tryIt ::~tryIt ()
{
   if(m_pInsertI!=NULL)
   {
      delete m_pInsertI;
      m_pInsertI=NULL
   }
}
bool createInsertI()
{
    m_pInsertI = returnFromSomeOtherFunction();
    return true;
}

bool insertI()
{
    // Over here if I use m_pInsertI anyhow my code fails with seg fault
    // even checking if(m_pInsertI==NULL) make the code throw seg fault
}

所以问题是碰到m_pInsertI到任何地方使我的代码抛出段。 故障(信号11)。 甚至使用GDB调试了代码,但没有任何有用的信息。

编译器是GCC

请帮忙。

听起来此类的实例不存在或未损坏。 这就是为什么您无法访问其任何成员,即使(m_pInsertI == NULL)检查引发异常也是如此。

在tryIt.cpp中不应该

bool createInsertI()

bool tryIt::createInsertI()

与insertI()相同

我看到以下两种可能性

  • returnFromSomeOtherFunction()已返回损坏的指针
  • 您正在使用编译器生成的方法复制实例(请参见下面的示例)

示例 (违反三项规则)

tryIt instance1; // allocates instance2.m_pInsertI

{
    tryIt instance2;
    instance1 = instance 2; // performs a shallow copy

} // here, instance2.m_pInsertI is deleted

instance1.insertI(); // access violation

建议:

是否是引起您问题的原因:不要实施手动内存管理。 只需将std::unique_ptr<CommandI>用作m_pInsertI ,因此您无需实现析构函数或复制构造函数/运算符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM