How to detect segmentation fault details using Valgrind?
I have a std::map< std::string, std::string> which initialized开发者_JAVA技巧 with some API call. When I'm trying to use this map I'm getting segmentation fault. How can I detect invalid code or what is invalid or any detail which can help me to fix problem? Code looks like this:
std::map< std::string, std::string> cont;
some_func( cont ); // getting parameter by reference and initialize it, someone corrupted memory (cont) inside this function
std::cout << cont[ "some_key" ] << '\n'; // segmentation fault here, cannot access "some_key"
you launch your application (compiled in debug mode) with the syntax:
valgrind yourapp
Valgrind will show you the stack backtrace of where segmentation fault occured. After that it's up to you to find what happened and to correct it.
In your code, regardless of valgrind, I would check what returns cont[ "some_key" ]
the most likely cause of your segfault is that the returned value is some wild pointer or not initialized at all. If so any try to access it like cont["some_key"][0]
would also cause a segmentation fault.
Another idea: what about the string keys in your map ? Is it possible that some of them silently (no exception) failed to allocate the data part of the string used as key. The std::map is not an hash table but just some ordered container. When searching a key it may need to access other keys and shit could happen there. To check that you can try to iterate on all keys in your map and show content (to see if problem specifically occurs with "some_key" or if you can access nothing in map.
You could also try with an unordered_map if your program does not need ordering to see if the behavior is the same.
In general I'm not sure how that line could be generating a seg fault: the bracket operator will always return a std::string (creating an empty one if needed) and it should always be valid for printing.
Is it possible that instead, the call stack you see is pointing to the next line to execute and it's dying in some_func? We don't see the code for it, so I can't say if it could be causing the problem.
Alternately is some_func
using char* (invokes temp std::string) to initialize strings in the map? It's possible that it could be introducing an invalid string into the map that "happens to work" for a while but when some_func returns it doesn't interact with the print well.
In addition to valgrind, you could try using a debugger in order to focus on your problem.
Set a breakpoint in some_func(cont)
line, and examine if cont
is a valid reference.
Moreover, have you considered what cont["some_key"]
is returning if some_key not present?
精彩评论