c++ returning dereference of a pointer causes Segmentation fault -


i have map pointer m, not local variable of function getmap, getmap returns dereference of pointer m, , when run code below, got segmentation fault (core dumped), why returning dereference of pointer causes segmentation fault.

std::map<int, std::string> *m;  const std::map<int, std::string>& getmap(){   m->insert(std::make_pair<int, std::string>(0, "hi"));   return *m; }  int main(){   const std::map<int, std::string>& m = getmap();   std::cout << "length: " << m.size() << std::endl; } 

m uninitialized global pointer. compiler gives default value of nullptr. invoke undefined behaviour when dereference - try read or write memory @ 0 address causes segmentation fault.

how fix:

  • define std::map object , make m point there

    std::map<int, std::string> glob_map; std::map<int, std::string> *m = &glob_map; ... remaining of code unchanged 
  • make getmap return temporary

    const std::map<int, std::string> getmap(){   std::map<int, std::string> localmap   localmap.insert(std::make_pair<int, std::string>(0, "hi"));   return m; }  int main(){   const std::map<int, std::string>& m = getmap();   std::cout << "length: " << m.size() << std::endl; } 

that rather advanced method, since use fact lifetime of temporary extended when directly affected reference. normal way copy temporary plain object (and let optimizing compiler elide unnecessary copy):

      const std::map<int, std::string> m = getmap(); 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo