Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect segmentation fault details using Valgrind?

I have a std::map< std::string, std::string> which initialized 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"
like image 983
Davit Siradeghyan Avatar asked Apr 21 '10 14:04

Davit Siradeghyan


People also ask

Can Valgrind detect segmentation fault?

GDB and Valgrind are great helpful tools to detect and correct segmentation fault and memory leaks.

How do you check for segmentation faults?

Use debuggers to diagnose segfaults Start your debugger with the command gdb core , and then use the backtrace command to see where the program was when it crashed. This simple trick will allow you to focus on that part of the code.

How does valgrind help in debugging?

Valgrind is a multipurpose code profiling and memory debugging tool for Linux when on the x86 and, as of version 3, AMD64, architectures. It allows you to run your program in Valgrind's own environment that monitors memory usage such as calls to malloc and free (or new and delete in C++).


1 Answers

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.

like image 118
kriss Avatar answered Oct 16 '22 15:10

kriss