I have a map<key_t, struct tr_n_t*> nodeTable and I’m trying to perform nodeTable[a] = someNode where a is of type typedef long key_t and someNode is of type o_t*.
I get a segmentation fault at the following point in the execution in stl_function.h:
/// One of the @link comparison_functors comparison functors@endlink.
template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; }
};
Source code:
#include <stdio.h>
#include <stdlib.h>
#include <map>
using namespace std;
typedef long key_t;
typedef struct tr_n_t {
key_t key;
map<key_t, struct tr_n_t *> nodeTable;
} o_t;
int main() {
o_t *o = (o_t *) malloc(sizeof(o_t));
o->nodeTable[1] = o;
return 0;
}
Am I not using the map right?
The problem is that because you initialize o using malloc, its memory is allocated but its constructor isn’t invoked.
Change it to
o_t *o = new o_t();because usingnewinstead ofmallocwill invoke the map’s constructor.