Seg Fault while doing memset

  • A+
Category:Languages

While running the below program, I am getting segfault. But if I comment memset, I am not getting seg fault. Not able to figure out the reason. What we can do instead of memset, if I need to clear the structure contents(such as value)?

#include <iostream> #include <cstring> #include <map> using namespace std;  struct test {     int value;     map<int, int> m; };  void print(test *ptr) {     cout << "map size() : " << ptr->m.size();     for(auto itr = ptr->m.begin(); itr != ptr->m.end(); ++itr)     {        }    }  int main() {     test obj;     memset(&obj, 0, sizeof(obj));     print(&obj); } 

 


std::map is not a POD structure, so it has internals (such as pointers and etc) which will be initialized in it's contructor.

When you call memset, you zeroed the entire structure, making any access to it undefined behavior.

And then you call function size(), which crash your code, because it tries to read any internal which is at zero address now.

Live Demo on cpp.sh

Instead of memset you should use specified method of std::map -> clear(), when you want to clear it.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: