2014/11/20

boost::shared_ptr Assertion `px != 0' failed.

a.out: /usr/local/include/boost/smart_ptr/shared_ptr.hpp:653: typename boost::detail::sp_member_access<T>::type boost::shared_ptr<T>::operator->() const [with T = classA, typename boost::detail::sp_member_access<T>::type = classA*]: Assertion `px != 0' failed.


When this assertion comes to me, this is because assigned object to the shared_ptr is NULL.

See sample code below.




#include <boost/shared_ptr.hpp>
#include <iostream>

class classA{
private:
    int number_;
public:
    classA(){ number_ = 1;}
public:
    int number() { return number_; }
};

typedef boost::shared_ptr<classA> classA_Ptr;

void makeNull(){
    std::cout << "@sshtel @@@@@@@@@ start function" << std::endl;

    classA_Ptr ap1(new classA());
    std::cout << "@sshtel @@@@@@@@@ ap1:" << ap1->number() <<  std::endl;

    classA *ca = 0;
    classA_Ptr ap2(ca);
    std::cout << "@sshtel @@@@@@@@@ ap2:" << ap2->number() <<  std::endl;

    std::cout << "@sshtel @@@@@@@@@ end of function" << std::endl;
}

int main(){
    makeNull();
    return 0;
}

-----------------------------------------------------------------------------


sshtel@rnd4svr4:~/test/SharedPtr$ ./a.out
@sshtel @@@@@@@@@ start function
@sshtel @@@@@@@@@ ap1:1
a.out: /usr/local/include/boost/smart_ptr/shared_ptr.hpp:653: typename boost::detail::sp_member_access<T>::type boost::shared_ptr<T>::operator->() const [with T = classA, typename boost::detail::sp_member_access<T>::type = classA*]: Assertion `px != 0' failed.
Aborted
sshtel@rnd4svr4:~/test/SharedPtr$
-----------------------------------------------------------------------------



To avoid this dangerous situation, you should check memory result of object allocation every time.





boost::shared_ptr<CLASS> c_ptr;
CLASS *c;
try{
    c = new CLASS();
    c_ptr.reset(c);
}
catch(std::bad_alloc){
    // exception
}

No comments:

Post a Comment