Debugger says pointer is NULL, C++ that it is not NULL



  • I have this very strange error I'm getting. Here is the destructor of my class, where mData is a pointer of the template T.

    @T* mData; // This is in the header file in my class decleration

    template<typename T>
    Chunk<T>::Chunk()
    {
    mData = 0;
    }

    template<typename T>
    Chunk<T>::~Chunk()
    {
    if(mData != 0)
    {
    delete [] mData;
    mData = 0;
    }
    }@

    In one of Chunk's function, I'm allocating: mData = new T[size]

    I'm getting a segmentation fault on the delete statement above. The weird thing is that my debugger (the one in Qt Creator) says that mData is 0, but C++ enters the if-statement because mData is apparently not-null. I've added a cout statement before the if-statement, and it also says that mData is not-null.

    So I always get a segfault with the delete statement. C++ says it is not-null and the debugger says it is null. Any idea what is going wrong?



  • You have a memory corruption somewhere else. You do not need to check for null before passing a value to delete.

    @T *data = nullptr;
    delete data;
    @

    Is perfectly valid in C++ and does nothing. Your if statement is not necessary and I would guess that mData is a dangling pointer or you have a more severe memory corruption somewhere.



  • Ahh, I didn't think that delete actually checked for NULL, I thought one has to do that manually. Thanks, I'll see if I can find the problem somewhere else.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.