shared_ptr Assertion px != 0 failed
Asked Answered
P

3

37

I have a fairly complex multi threaded application (server) that from time to time will crash due to an assert:

/usr/include/boost/smart_ptr/shared_ptr.hpp:418: T* boost::shared_ptr< <template-parameter-1-1> >::operator->() const [with T = msg::Player]: Assertion `px != 0' failed.

I have been unable to pinpoint the cause and was wondering if this is a problem with boost::shared_ptr or it is me?

I tried g++ 4.4.3-4ubuntu5 and llvm-g++ (GCC) 4.2.1 with optimization and without optimization and libboost1.40-dev (= 1.40.0-4ubuntu4).

Potentiality answered 22/8, 2010 at 10:48 Comment(3)
multithreading bugs are hard to pinpoint. Since you're on linux, there's no reason to not use valgrind - it'll help you greatly finding the bug.Occidentalize
I am using valgrind extensively and I get zero errors (with memcheck) until the assert occurs. I am still learning how to interpret drd error messages as most of them (conflict load/store on boolean/integer types) seem not a problem.Potentiality
Just hit that issue in debug, and was caused by variable watch trying to access uninitialized yet shared_ptr variable. The debugger watch did not contain the assertion.Scheller
H
41

There should be no problem with using boost::shared_ptr as long as you initialize your shared pointers correctly and use the same memory management context for all your shared object libraries.

In your case you are trying to use an uninitialized shared pointer.

boost::shared_ptr<Obj> obj;
obj->Something(); // assertion failed

boost::shared_ptr<Obj> obj(new Obj);
obj->Something(); // ok

I would advise to initialize them right on declaration whenever possible. Exception handling can create a lot of "invisible" paths for the code to run and it might be quite difficult to identify the non initialized shared pointers.

PS: There are other issues if you load/unload modules where shared_ptr are in use leading to chaos. This is very hard to solve but in this case you would have a non zero pointer. This is not what is happening to you right now.

PPS: The pattern used is called RAII (Resource Acquisition Is Initialization)

Haugh answered 22/8, 2010 at 11:55 Comment(0)
B
3

you might want to make sure that you

always use a named smart pointer variable to hold the result of new

like it is recommended here: boost::shared_ptr - Best Practices

Regards, Jonny

Ballenger answered 22/4, 2011 at 20:40 Comment(0)
L
0

Here's to reviving an ancient question. I just hit this, and it was due to a timing issue. I was trying to use the shared_ptr from one thread before I'd finished initializing it in another.

So if someone hits the above message, check your timing to ensure your shared_ptr has been initialized.

Lilli answered 22/2, 2019 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.