Segmentation fault while iterating std::map through callback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void call(boost::function<void ()> f) {
f();
}
void end() {
cout << "End..." << endl;
}
void fn(map<string, string> &m, map<string, string>::iterator i) {
cout << "i->first: " << i->first << endl;
if (++i == m.end()) {
end();
} else {
call(boost::bind(&fn, m, i));
// fn(m, i);
}
}
int main() {
//Please don't consider the case of empty map.
map<string, string> m;
m["abc"] = "asasd";
m["bcd"] = "sasas";
m["cde"] = "jdssd";

call(boost::bind(&fn, m, m.begin()));
// fn(m, m.begin());
}


i->first: abc
i->first: bcd
i->first: cde
segmentation fault occurs here.


If I do it without callback(commented code) its fine.
Anyone please help me find where I have gone wrong.

Thanks in advance.
Please fix the formatting in your post. I can't figure out what you are trying to do with this call back. Please give a description of what your goal is.
By default, boost::bind() makes a copy of the parameters that it needs to pass to
the function. Therefore, line 23 makes a copy of the map<> and line 12 makes a copy
of the map<>. You then compare the iterator i, which is an iterator into the original map,
against end() called on a copy. The condition will never be true.

To fix use boost::ref:

 
call( boost::bind( &fn, boost::ref( m ), m.begin() );


This now stores only a reference to the container and not the container itself.
Thanks so much for the reply, it solved the problem.
Topic archived. No new replies allowed.