How To Determine Seg Fault? - c++

I have an interesting Segmentation Fault. It occurs at an unknown place in my code. The code is fairly simple, two objects, and one general function. The function is supposed to create a graph of the objects. When I run the code with just a main calling the function, I get a seg fault and the following line of code in GDB.
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff758a02c in free () from /lib/x86_64-linux-gnu/libc.so.6
When I add a line into the main right before the function call that is simply cout << "Check"; I still get a segmentation fault, but the check does not appear in output. Really lost here. What should I try next?
EDIT:
Thanks for the help with using flush. I've found the area in the code that's causing the seg fault. The functions I'm using are new to me though so I'm still a little lost. Anyone see a bug?
const char* inFile = inFileP.c_str();
list<CContinent> world;
CCountry *homeCountry = new CCountry;
CCountry *neighborCountry = new CCountry;
fstream filestr;
filestr.open(inFile, fstream::in | fstream::out | fstream::app);
string line;

From painful experience, when a crash happens in malloc or free it is because of heap corruption. Any of the usual suspects can cause heap corruption - allocate 10 bytes, write 11 - free, then write to free'd memory, double free, et.al.

Valgrind is a useful tool for debugging a program.
At the first view I don't see a initialization for world variable.

Related

Segmentation fault debugger error message meaning?

I am learning c++ and I have a segmentation fault with my code. I ran the debugger and I got the following error message which I am struggling to understand.
Program received signal SIGSEGV, Segmentation fault. 0x0000000008002e3e in std::__uniq_ptr_impl<TreeNode<int>, std::default_delete<TreeNode<int> > >::_M_ptr (this=0x8) at /usr/include/c++/7/bits/unique_ptr.h:147
147 pointer _M_ptr() const { return std::get<0>(_M_t); }
Does this mean the segmentation fault is occurring in line 147 in my TreeNode class? If so, the line 147 is empty.
Can someone please clarify.
Edit: after following #HolyBlackCats advice I typed in bt and got the following message.
#0 0x0000000008002e3e in std::__uniq_ptr_impl<TreeNode<int>, std::default_delete<TreeNode<int> > >::_M_ptr (this=0x8) at /usr/include/c++/7/bits/unique_ptr.h:147
#1 0x0000000008002680 in std::unique_ptr<TreeNode<int>, std::default_delete<TreeNode<int> > >::get (this=0x8) at /usr/include/c++/7/bits/unique_ptr.h:337
#2 0x0000000008001c55 in BinarySearchTree<int>::begin (this=0x7ffffffedf48) at tree.h:99
#3 0x0000000008000d98 in main () at TestTreeD.cpp:20
I still do not understand what this means.
As the error message states, the segfault occurred when executing code compiled from line 147 of the C++ library header file.
The backtrace shows the execution stack at the point where backtrace occurs.
A backtrace does not always give you a full explanation for the reasons for your segfault. Unfortunately, C++ is not that easy. The backtrace only gives you the starting clues for investigating the reason for the crash. A backtrace is only the starting point for our debugging. Where you go from there depends on what you know and your experience.
Sometimes even the backtrace itself is garbage, because the stack was corrupted.
And at other times the backtrace will be good, but not have anything to tell you about the reason for the segfault, but it will tell you the how you wound up in that part of the code. So, for example, you would use this information to set a breakpoint earlier in the code, before the crash, and when execution stops there, you can analyze and inspect the values of all objects and variables, and see if anything seems out of place, or if there's something wrong. What's "something wrong" means is going to be entirely up to you to determine, based on the exact details of your application.
I could find only one clue that's apparent by inspecting your shown backtrace, that would be stack frame #1:
#1 0x0000000008002680 in std::unique_ptr<TreeNode<int>,
std::default_delete<TreeNode<int> > >::get (this=0x8)
==========
According to this backtrace, the code is executing an object at memory address 0x8. This is, obviously, complete nonsense. It's quite common to see this of 0x0, a.k.a. a null pointer, when picking up the flaming wreckage of a backtrace. 0x8 is close enough to indicate memory corruption. Probably some object that has a unique_ptr as a class member, the pointer to this object is null, and the code is attempting to invoke a method of the unique_ptr, which is at offset 0x8 in the class that contains it.
So, at this point, the shown code most likely used a garbage pointer, or an uninitialized reference, or some other logical error to invoke a method through a bad pointer or reference.
Your next step would be to set a breakpoint wherever stack frame #2 is, that invoked some operation on some bogus unique_ptr it got somewhere. Based on what you see there, you will either find more clues, or, after inspecting the surrounding code, be able to determine the underlying bug.
Good luck.
I would like to point out that this occurs if one is trying to initialize a static const-member through moving an initialized instance of std::unique_ptr into the uninitialized member, which will cause such behaviour.
Here an example of what I mean:
class SomeClass
{
private:
static const std::unique_ptr<string> RESOURCE;
public:
SomeClass() = default;
~SomeClass() {};
private:
static std::unique_ptr<string>&& initResource()
{ return std::unique_ptr<string>(new string{"fdsa"}); }
};
const std::unique_ptr<string> SomeClass::RESOURCE = SomeClass::initResource();
int main(int argc, char const* argv[])
{
return 0;
}
Try compiling this code with the debug-flag (with g++ it's the -g-flag) and run it using gdb, and you will see quite the similar behaviour as one may observe below:
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555638 in std::__uniq_ptr_impl<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::default_delete<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >::_M_ptr (this=0x0) at /usr/include/c++/7/bits/unique_ptr.h:147
147 pointer _M_ptr() const { return std::get<0>(_M_t); }
Basically in order to fix this, simply remove the rvalue reference (<type>&&) from methods like SomeClass::initResource() and/or do not use things that enforce a moving operation such as std::move() in those situations where initialization is supposed to happen.

program received signal SIGSEGV, segmentation fault

I am running a program in multi threaded environment it fails at some point. when i tried it with gdb than it is shoing the following error.
program received signal SIGSEGV, segmentation fault.
[switching to thread 0x7fff677b700 (LWP 2777)] 0x00007ffff7aa42b9 in
process_incomplete_rows (resultset=0x507950) at c/mgmt.c:479 479
c/mgmt.c: No such file or directory.
mgmt.c file is there and this code is working fine for some options but 2 or three options its giving this error. What could be the cause of this error. Its error in comiplation or in coe? or its error while accessing some data?
A segmentation fault is a runtime error that is usually due to referencing an invalid pointer. Usually that invalid pointer has never been initialized, but sometimes it is reusing an old pointer or writing past the end of an allocated memory chunk (such as past the end of a string).
It probably means that your node variable is either NULL or corrupted. Run your program in the debugger, stepping through it from some point prior to the crash up until it and see where you've messed it up. Or use one of the automated tools like Purify or Insure++ to track it down for you.

Weird segfault with std::malloc

I'm getting a segfault with the following line of code:
char* addr = (char*)std::malloc(bytes);
When running GDB I see that bytes has a value of 851984. As far as I know that shouldn't be a big deal. I can't seen anything wrong with it for the life of me. Anybody have some suggestions?
The actual segfault error is:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff674dd75 in malloc_consolidate (av=0x7ffff6a87720) at malloc.c:4254
There is (most likely) an issue somewhere earlier in your code which is corrupting heap structures, causing malloc to fail on allocation. You should try using a memory error detection tool like valgrind to debug this issue.

Possible reasons for segmentation fault on function exit

What possible reasons can you think of for a segmentation fault on exiting a function in C++? What I mean by that is, that I have a reproducible segmentation fault in a C++ program, and when I investigate using GDB is says
Program received signal SIGSEGV, Segmentation fault.
FooBar (bla=...) at foo.cpp:59
59 }
where the indicated line contains the closing bracket of my function.
There could be many reasons of this. Run program under Valgrind and most likely it will tell you exact reason or at least will help to investigate and narrow down the problem.
It's quite likely a buffer overrun on some buffer located on your stack. This overwrites the return address, so when your code tries to return to the previous stack frame, it instead jumps to some random address which is more likely than not non-executable, so you get a segmentation fault.
But without seeing some more code or more information about the crash, it's impossible to say what the exact cause is.
My first guess is the destructor of a class is freeing an invalid pointer.
in my case I had an std::thread that had not been properly joined.

C++ segmentation fault when trying to output object functions

I am attempting to output functions common to a set of objects that share a base class and I am having some difficulty. When the objects are instantiated they are stored in an array and then I am attempting with the following code to execute functionality common to all the objects in this loop:
if ( truck <= v ) // all types of trucks
vptr is an array of objects and the functions in the loop are common to all the objects. The code compiles fine but when I run it I get a segmentation fault when it enters this loop. I'm fairly confident that the call to the first function in this loop is what is causing the problem.
this is how I have instantiated the objects in a previous loop:
vptr[ i ] = new Vehicle( sn, pc );
I should also mention, I'm sorry I forgot to be clear from the beginning, that in this array each object is of a different class. They all share a base class but they are derived objects of that class. Sorry for forgetting that probably important piece of information.
thanks
nmr
dynamic_cast to a pointer type returns a null pointer (aka 0, NULL) if the object isn't of the specified type. You must check the pointer before using it, or use a reference type (which throws an exception on failure instead):
if (Truck* p = dyanmic_cast<Truck*>(vptr[i])) {
// use the pointer here
}
else {
// vptr[i] doesn't point to a Truck
}
(Notice the nice effect of the correctly-typed pointer being scoped for you, take advantage of this when you can to improve readability.)
If you use a debugger, you can easily figure out which call is causing the segmentation fault and even examine memory to see if you have a null pointer, etc.
GCC with GDB is a good example. Try this--first build your application with debugging info (to do this you add the -g switch to your compiler):
gcc -g test.c -o myProgramName
Now launch GDB:
gdb myProgramName
At the first GDB prompt, enter the 'r' command to run the program:
(gdb) r
Then, when you reach the segfault, use the 'bt' command to view the stack trace and find out where the program was when it had the bad memory access:
Program received signal SIGSEGV, Segmentation fault.
0x08048380 in testFunction2 () at test.c:17
17 *test = 1;
(gdb) bt
#0 0x08048380 in testFunction2 () at test.c:17
#1 0x0804836e in testFunction1 () at test.c:10
#2 0x0804835a in main () at test.c:5
When you compile with debugging enabled, it lets you see the source file, line number, and the actual code that caused the crash. Learning to use a debugger makes hunting down segmentation faults really easy.
Debuggers also let you examine memory--with the above example, I can check the value of the 'test' pointer:
(gdb) print test
$1 = 0x0
Whoops, the pointer was NULL when I tried to change the memory it referenced, thus I was accessing memory my program wasn't allowed to touch, causing a segmentation fault.
Try the 'print' command with objects as well--GDB is smart enough to actually break the object down and show you the value of each of the object's members. Additionally, you can use the 'printf' command to print strings, etc. while you're debugging your program.
Hope this is helpful,
Maha