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 therestd::map<int, std::string> glob_map; std::map<int, std::string> *m = &glob_map; ... remaining of code unchanged
make
getmap
return temporaryconst 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();