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 pointerclass 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 }
-