简体   繁体   English

C ++代码抛出段。 故障

[英]C++ code throwing Seg. Fault

I have a C++ code as follow: 我有一个C ++代码,如下所示:

tryIt.h file tryIt.h文件

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

tryIt.cpp file 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
}

So the issue is touching m_pInsertI anywhere make my code throw Seg. 所以问题是碰到m_pInsertI到任何地方使我的代码抛出段。 fault (Signal 11). 故障(信号11)。 Even debugged the code with GDB but didn't got any useful info. 甚至使用GDB调试了代码,但没有任何有用的信息。

Compiler is GCC 编译器是GCC

Please help. 请帮忙。

Sounds like the instance of this class does not exist or damaged. 听起来此类的实例不存在或未损坏。 That is why you can't access any of its members and even if(m_pInsertI==NULL) check raises the exception. 这就是为什么您无法访问其任何成员,即使(m_pInsertI == NULL)检查引发异常也是如此。

in tryIt.cpp shouldn't 在tryIt.cpp中不应该

bool createInsertI()

be

bool tryIt::createInsertI()

same with insertI() 与insertI()相同

I see the following two possibilities : 我看到以下两种可能性

  • returnFromSomeOtherFunction() already returns a corrupted pointer returnFromSomeOtherFunction()已返回损坏的指针
  • You are copying your instance using the compiler generated methods (see example below) 您正在使用编译器生成的方法复制实例(请参见下面的示例)

Example (Rule of three violation) 示例 (违反三项规则)

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

Recommendation: 建议:

Whether or not this is cause your problem: Do not implement manual memory management. 是否是引起您问题的原因:不要实施手动内存管理。 Simply use a std::unique_ptr<CommandI> for m_pInsertI instead, so you do not need to implement the destructor or copy constructors/operators. 只需将std::unique_ptr<CommandI>用作m_pInsertI ,因此您无需实现析构函数或复制构造函数/运算符。

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

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