tags:

views:

146

answers:

4
for(ItemTemplateListIterator iter = item_template_list.begin(); iter != item_template_list.end(); ++iter) {
    int id = iter->first;
    string description = iter->second->description;
    some_file_stream << id << endl;
    some_file_stream << description << endl;

}

Where item_template_list is a map of <int, MyClass*>, ItemTemplateListIterator is a typedef for a const_iterator of map<int, MyClass*> and MyClass has a public string property called description.

+1  A: 

I'll take a shot.

One of the MyClass* (pointers) has a "junk" (incorrect) value when you try to access it and boo-m. Segfault city.

As commented, you can store the full object in the map and not bother with pointers.

JustBoo
Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements. Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased.
JustBoo
+2  A: 

What very likely happened is that the object pointers that you stored in the map are not valid anymore (because the memory was deallocated elsewhere). Attempting to access a deallocated memory area causes a segfault. Not valid is meaning either NULL or having a so-called "dangling pointer".

Maybe also you are modifying the map or objects in the map in another thread while iterating through it.

There is too little code here for me to help you more.

jdehaan
This code is single threaded. I'll check for if it's deallocated anywhere.
Macha
A: 

one of (iter->second) == null

Moisei
A: 

The reason this is segfault is probably because the MyClass* is null or has been freed and has garbage value.

You can easily find out if it's null:

MyClass * obj = iter->second;
if (obj == null) {
    cerr << "Unexpected null pointer" << endl;
} else {
    string description = obj->description;
    some_file_stream << id << endl;
    some_file_stream << description << endl;
}

However, you still need to go through the rest of your code that populates the list and find out why it's not what you expected it to be.

Overall I'd say unless you're aiming to eliminate unnecessary copying of objects you'll be safer to store actual objects in the list and just make sure your copy constructor can handle them.