Iterating on std::map results in segmentation fault

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wangkhem
    New Member
    • Jan 2010
    • 2

    #1

    Iterating on std::map results in segmentation fault

    Code:
    void call(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(bind(&fn, m, i));
        }
    }
    int main() {
        map<string, string> m;
        m["abc"] = "asasd";
        m["bcd"] = "sasas";
        m["cde"] = "jdssd";
    
        call(bind(&fn, m, m.begin()));
    }
    The above code results in segmentation fault. Kindly help me find where im I wrong.
  • akdemirc
    New Member
    • Sep 2008
    • 26

    #2
    in fn function you are trying to access the first element of the iterator without checking its value (when it reaches the end of map, it will cause segmentation if you try to print), try this

    Code:
    if (i != m.end())
    { 
         cout << "i->first: " << i->first << endl; 
    }

    Comment

    • wangkhem
      New Member
      • Jan 2010
      • 2

      #3
      Originally posted by akdemirc
      in fn function you are trying to access the first element of the iterator without checking its value (when it reaches the end of map, it will cause segmentation if you try to print), try this

      Code:
      if (i != m.end())
      { 
           cout << "i->first: " << i->first << endl; 
      }
      Thanks for your kind reply. Sorry for not being clear with my question. Im not considering the case when map is empty it ll be handled separately.
      The following code will excutes fine.
      Code:
      void fn(map<string, string> &m, map<string, string>::iterator i) {
          cout << "i->first: " << i->first << endl;
          if (++i == m.end()) {
              end();
          } else {
              // call(bind(&fn, m, i));
              fn(m, i);
          }
      }
      int main() {
          map<string, string> m;
          m["abc"] = "asasd";
          m["bcd"] = "sasas";
          m["cde"] = "jdssd";
      
          // call(bind(&fn, m, m.begin()));
          fn(m, m.begin());
      }
      But with callbacks why am I getting a segmentation fault?

      Comment

      Working...