c++ - I don't understand my memory error in reference counting -
i implementing contrived example follow this tutorial on reference counting:
struct bar { bar () : refs(1) {} int x; int y; int z; unsigned refs; }; class foo { public: foo () { bar = new bar; bar->x = 5; bar->y = 10; bar->z = 15; } foo (const foo &other) : bar(other.bar) { ++bar->refs; } foo& operator = (const foo &other) { if (&other != this) { if (--bar->refs < 1) delete bar; bar = other.bar; // fix it: ++bar->refs; } return *this; } ~foo () { if (--bar->refs < 1) delete bar; } private: bar *bar; }; int main(void) { foo a; foo b = a; foo c; c = b; } valgrind gives me following error, although no memory leaked. me interpret it?
==6814== error summary: 3 errors 3 contexts (suppressed: 2 2) ==6814== ==6814== 1 errors in context 1 of 3: ==6814== invalid read of size 4 ==6814== @ 0x400914: foo::~foo() (ref-count.cpp:41) ==6814== 0x4007ca: main (ref-count.cpp:54) ==6814== address 0x4c2d04c 12 bytes inside block of size 16 free'd ==6814== @ 0x4a07991: operator delete(void*) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so) ==6814== 0x40092e: foo::~foo() (ref-count.cpp:42) ==6814== 0x4007be: main (ref-count.cpp:52) ==6814== ==6814== ==6814== 1 errors in context 2 of 3: ==6814== invalid write of size 4 ==6814== @ 0x400911: foo::~foo() (ref-count.cpp:41) ==6814== 0x4007ca: main (ref-count.cpp:54) ==6814== address 0x4c2d04c 12 bytes inside block of size 16 free'd ==6814== @ 0x4a07991: operator delete(void*) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so) ==6814== 0x40092e: foo::~foo() (ref-count.cpp:42) ==6814== 0x4007be: main (ref-count.cpp:52) ==6814== ==6814== ==6814== 1 errors in context 3 of 3: ==6814== invalid read of size 4 ==6814== @ 0x40090b: foo::~foo() (ref-count.cpp:41) ==6814== 0x4007ca: main (ref-count.cpp:54) ==6814== address 0x4c2d04c 12 bytes inside block of size 16 free'd ==6814== @ 0x4a07991: operator delete(void*) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so) ==6814== 0x40092e: foo::~foo() (ref-count.cpp:42) ==6814== 0x4007be: main (ref-count.cpp:52) edit: see commented line in operator = fix.
the copy-assignment operator needs increment reference count.
Comments
Post a Comment