2

I have been pulling my hair for a few hours trying to understand a puzzling segfault. The exact same code works in my object constructor but not in the object's method where it's supposed to be: I get a segfault at run time.

Hopefully, I have not snipped anything relevant:

stud.hpp:

#include <boost/ptr_container/ptr_map.hpp>

namespace my {

class person {
    person(long id); // implemented in another file.
    std::string name;
};

class Stud {
    Stud();
    boost::ptr_map<long, my::person> people;
    my::person* by_id(long id);
};
}

stud.cpp:

#include "stud.hpp"

namespace my {

Stud::Stud() {
    // debug:
    long id = 143; // valid id.
    my::person* p = new my::person(id);
    people.insert(id, p);
    std::cout << "Inserted in constructor. All OK." << std::endl;
}

my::person* Stud::by_id(long id__) {
    long id = 142; // valid id.
    my::person* p = new my::person(id);
    std::cout << p->name << "All OK so far..." << std::endl;
    people.insert(id, p); // segfaults.
    std::cout << "The application segfaults before arriving here." << std::endl;
    return p;
    // This method is eventually supposed to check
    // if a specific id is present in the map
    // and return it if it is.
    // Otherwise create the object, insert into the map
    // and return the new pointer.

}

}

backtrace:

#0  0x00007fffe8d3986f in std::less<long>::operator()(long const&, long const&) const ()
   from /usr/local/lib/plugins/libstud.so.0
#1  0x00007fffe8d394a5 in std::_Rb_tree<long, std::pair<long const, void*>, std::_Select1st<std::pair<long const, void*> >, std::less<long>, std::allocator<std::pair<long const, void*> > >::_M_insert_unique(std::pair<long const, void*> const&) ()

Request: solve my problem for me! ;)

Now, more seriously:
Questions:
does the ptr_map people need to be initialized in any way in the constructor?
Why would the same insert code work in the constructor but not in the method?
What can cause a ptr_map insert to segfault the application?

Edit:

The application is actually a plugin for an cppcms-based application. The whole application is already starting to get fairly complex and I cannot reasonably post everything. However, what I am seeing in my IDE is more or less what I wrote above and that's why I am as perplexed as you seem to be (or the other way around!). I am using hard-coded values for debugging, not relying on the id passed to the method. If I comment out the insert line, the application runs fine. The std::cout above it print, but the one below doesn't. The backtrace says something about std::less that I don't understand. I did my best to summarize the problem. I have already spent many hours on it and I am truly perplexed. I appreciate your understanding and your help. If need be, I'll think about more drastic, time-consuming ways to debug the application... Meanwhile...

4

0 回答 0