简体   繁体   中英

C++ code throwing Seg. Fault

I have a C++ code as follow:

tryIt.h file

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

tryIt.cpp file

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. fault (Signal 11). Even debugged the code with GDB but didn't got any useful info.

Compiler is 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.

in tryIt.cpp shouldn't

bool createInsertI()

be

bool tryIt::createInsertI()

same with insertI()

I see the following two possibilities :

  • returnFromSomeOtherFunction() already returns a corrupted pointer
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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