I have this simple code
#include<memory>
class SLLNode{
public:
SLLNode(const int& d){
data_ = d;
}
std::shared_ptr<SLLNode> next_;
int data_;
};
int main(){
std::shared_ptr<SLLNode> head(new SLLNode(1));
head->next_.reset(new SLLNode(2));
*head = *(head->next_);
return 0;
}
Valgrind is complaining about invalid read in my case.
==17312== Invalid read of size 4
==17312== at 0x108EF3: SLLNode::operator=(SLLNode const&) (test_shared_ptr.cpp:3)
==17312== by 0x108DA3: main (test_shared_ptr.cpp:16)
==17312== Address 0x5b7dd50 is 16 bytes inside a block of size 24 free'd
==17312== at 0x4C3123B: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17312== by 0x109511: std::_Sp_counted_ptr<SLLNode*, (__gnu_cxx::_Lock_policy)2>::_M_dispose() (shared_ptr_base.h:376)
==17312== by 0x1090DF: std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release() (shared_ptr_base.h:154)
==17312== by 0x109061: std::__shared_count<(__gnu_cxx::_Lock_policy)2>::operator=(std::__shared_count<(__gnu_cxx::_Lock_policy)2> const&) (shared_ptr_base.h:703)
==17312== by 0x108E9A: std::__shared_ptr<SLLNode, (__gnu_cxx::_Lock_policy)2>::operator=(std::__shared_ptr<SLLNode, (__gnu_cxx::_Lock_policy)2> const&) (shared_ptr_base.h:1034)
==17312== by 0x108EC4: std::shared_ptr<SLLNode>::operator=(std::shared_ptr<SLLNode> const&) (shared_ptr.h:93)
==17312== by 0x108EEE: SLLNode::operator=(SLLNode const&) (test_shared_ptr.cpp:3)
==17312== by 0x108DA3: main (test_shared_ptr.cpp:16)
==17312== Block was alloc'd at
==17312== at 0x4C3017F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17312== by 0x108D5C: main (test_shared_ptr.cpp:15)
The command I use is:
valgrind --tool=memcheck ./test_shared_ptr
The =operator seems to cause this issue only when I use nested shared_ptr. I was expecting the data from the ptr head to be released and replace by the one from the ptr head.next_, but it appears that something else is happening since I have this invalid read. I want to replace the data pointed by head (and not head itself) since this head ptr could be a copy of another shared_ptr of head.
The implicitly defined assignment operator looks like this:
SLLNode& SLLNode::operator=(const SLLNode& other) {
next_ = other.next_;
data_ = other.data_;
return *this;
}
In your example, other
is SLLNode(2)
, and it's only kept alive by a reference from head->next_
. other.next_
is NULL
.
The first assignment above sets head->next_
to NULL
, which causes SLLNode(2)
to be destroyed, and leaves other
a dangling reference. The next line exhibits undefined behavior by way of accessing an object after its lifetime has ended.