Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QSharedPointer crash in Linux



  • The code at below works fine in Windows, but crash in Linux. Please advice what I do wrong and how the problem can be fixed.
    I get the following error message
    free(): invalid pointer

    class Process {
    
    public:
       Process();
       MyStruct m_data;
    };
    
    Process::Process()
    {
       QSharedPointer<MyStruct>  dataPtr = QSharedPointer<MyStruct>(&m_data);   <---Here crash
    }
    


  • Why are you creating a shared pointer to a class member variable?

    From the documentation:
    QSharedPointer will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it.

    When the two QSharedPointer instances in Process::Process() go out of scope at the end of the function, delete will be called on &m_data, which wasn't allocated with new.



  • @jeremy_k said in QSharedPointer crash in Linux:

    Why are you creating a shared pointer to a class member variable?

    So the correct approach will be as below, rigth?:

    class Process {
    
    public:
       Process();
       MyStruct *m_data;
    };
    
    Process::Process()
    {
       m_data = new MyStruct();
       QSharedPointer<MyStruct>  dataPtr = QSharedPointer<MyStruct>(m_data);
    }
    


  • @aliks-os said in QSharedPointer crash in Linux:

    @jeremy_k said in QSharedPointer crash in Linux:

    Why are you creating a shared pointer to a class member variable?
    

    So the correct approach will be as below, rigth?:

    class Process {
    
    public:
       Process();
       MyStruct *m_data;
    };
    
    Process::Process()
    {
       m_data = new MyStruct();
       QSharedPointer<MyStruct>  dataPtr = QSharedPointer<MyStruct>(m_data);
    }
    

    That depends on the goal, but I would guess not. As is, the instance of MyStruct will be created and deleted in the Process constructor. At that point, m_data will be a dangling pointer. It might be easier to understand a simplified form:

    MyStruct *dangling;
    void f()
    {
      QSharedPointer<MyStruct> dataPtr(new MyStruct);
      dangling = dataPtr.data();
      // MyStruct instance deleted here
      // dangling doesn't point to a valid object
    }
    


  • @jeremy_k
    yes you are right. Many thanks for your help. I have understood my mistake. In my case better to restruct the workflow of my code.
    But I still wondering why the first version of my code works in windows but not in linux. )))



  • Chance plus the choices made by the compiler and runtime sometimes appear to produce working programs for undefined behavior.


Log in to reply