0

I am using boost unordered hashmap in C++ and I am unable to add elements to my hash map (my program has a segmentation fault). I am very new to C++ and the majority of my code (except the hash map handling) is C code. Could you please point out the problem.

// my simplified code

struct Record
{
        char *data;

};

typedef boost::unordered_map<std::string, std::vector<Record*> > MAP;
typedef std::pair<std::string,std::vector<Record*> > PAIR;

struct OuterRelation
{
        short num_keys;
        short join_key_ndx;
        MAP hash_table;
};

OuterRelation *outer_relation = (OuterRelation *) malloc (sizeof(OuterRelation)) ;

Record *new = (Record *) malloc(sizeof(Record));
new->data = "somestring";

outer_relation->hash_table[new->data].push_back(new);

The problem is in the last line.

1 Answer 1

3

STOP USING malloc. That's for C. Correct syntax would be:

OuterRelation *outer_relation = new OuterRelation;

Your use of malloc has allocated enough space for the OuterRelation struct alone. This might be enough if the struct contained only plain-old-data. However, the hash_table member is a class and using malloc has left it uninitialised.

new is (at its most basic) a combination of malloc and a call to the new'd object's constructor. The constructor for your struct will in turn call the constructors of its members, including the map. The map's constructor will initialise its data members.

You also need to stop using new as a variable name. That clashes with the new C++ keyword.

Sign up to request clarification or add additional context in comments.

2 Comments

If I would like to free OuterRelation at the end of my program, does C++ offer free(outer_relation) construct? Is it a common practice to do such frees or do I leave it to the garbage collector?
Call delete outer_relation;. delete calls the object's destructor then frees its memory. C++ has no garbage collection. (Well, technically garbage collection libraries exist, but I haven't seen code which uses one yet.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.