std::tr1::shared_ptr and dynamic_cast - c++

I use shared_ptr with constructing an object like this:
std::tr1::shared_ptr<RawClusterBase> rawCluster(new RawClusterBase());
// ...
rawCluster->addLabel(p->userFriendlyTerms());
// ...
const TokenizedDocument * tokenizedDoc
= (TokenizedDocument *)documents.at(i);
const RawDocument * rawDoc
= dynamic_cast<const RawDocument *>(tokenizedDoc->getProperty(
TokenizedDocument::_PROPERTY_RAW_DOCUMENT));
rawCluster->addDocument(rawDoc);
I get a segmentation fault on the line with the dynamic_cast:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b92429 in __dynamic_cast () from /usr/lib/libstdc++.so.6
(gdb) backtrace
#0 0x00007ffff7b92429 in __dynamic_cast () from /usr/lib/libstdc++.so.6
#1 0x0000000000444aa5 in main (argc=1, argv=0x7fffffffe258) at clustering/document_test.cpp:271
Can anybody give me a pointer how to solve that? I have a other section in my project
where I use dynamic_cast to analyze subclass. I also plan to use the shared_ptr there
but I am afraid I would run into the same troubles. Is dynamic_cast not working with shared_ptr?
Any hint is greatly appreciated!

The problem isn't evident from the provided code, but in all likelihood, either:
documents.at(i) doesn't return a valid TokenizedDocument pointer
tokenizedDoc->getProperty(TokenizedDocument::_PROPERTY_RAW_DOCUMENT) is returning an invalid pointer.

It's hard to tell what might be going wrong. It could be due to a buffer overrun or access to a deallocated pointer, because such things are likely to overwrite a vtable pointer (which occurs at the beginning of an object). Try running the program in Valgrind.
Typically dynamic_cast shouldn't crash. It returns nullptr (or throws std::bad_cast when using references) if the cast is invalid, or it fails to compile if the cast is totally impossible. But it doesn't invoke UB, so I'd look elsewhere for the culprit.

Don't use such old-C cast in your C++ code:
const TokenizedDocument * tokenizedDoc
= (TokenizedDocument *)documents.at(i);
Looks like your document.at(i) returns pointer to something else. Try to remove (TokenizedDocument *) completely.

Related

How to return Segmentation fault in my custom class in C++?

I am building Stack Class using Linked List manually. I want to return Segmentation fault when the top() function is called on an empty Stack. How can I do that? Or some other error that I can return.
Segmentation faults are triggered by hardware and handled by the OS. You do not trigger them manually.
You can throw an exception: http://www.cplusplus.com/doc/tutorial/exceptions/ or you can decide on some value which indicates an error and return that.
If you have a pointer to the first element that is null or dangling (i.e. pointing to uninitialized/freed memory) when the list is empty, you can also dereference it as if there was a value. This will sometimes cause a segmentation fault and sometimes return bogus data. In this case it is up to the user not to call top on an empty list. Generally code does not guarantee to segfault in certain cases. Rather it sometimes happens when the hardware manages to catch a bad memory access.
If you post your code it will be easier to say how you can report the error in your concrete case.
How can I do that?
You could raise(SIGSEGV). Alternatively abort() the execution.
You could also force read from invalid memory address, for example from the null pointer with like: *(volatile int*)0;.
Or some other error that I can return.
You should definitely not cause a segmentation fault condition intentionally in your program. Instead use an exception.

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.

What actually happens when calling a getter function for an instance variable(that is an object)?

Lately I have had a constant battle with a function causing a SEGFAULT randomly. After doing some extra work in trying to find out the problem, I have come up with the following:
All code posted via pastebin:
BUILD 1:This is the original code, it causes the following SEGFAULT (given after link)
http://pastebin.com/huzcqnDA
SEGFAULT:
#0 6FC657AC libstdc++-6!_ZNKSs4_Rep12_M_is_leakedEv() (Z:\CPP Programming\CodeBlocks\MinGW\bin\libstdc++-6.dll:??)
#1 6FC89FDB libstdc++-6!_ZNSs4_Rep7_M_grabERKSaIcES2_() (Z:\CPP Programming\CodeBlocks\MinGW\bin\libstdc++-6.dll:??)
#2 6FC8C0E7 libstdc++-6!_ZNSsC1ERKSs() (Z:\CPP Programming\CodeBlocks\MinGW\bin\libstdc++-6.dll:??)
#3 0094A470 Carp::Sprite::Sprite(this=0x27fae8, s=...) (Z:/CPP Programming/Carperon/Source/Carp/Engine/StructL2.hpp:28)
#4 00944E98 Carp::Item::_spr(this=0x1277eb80) (Z:/CPP Programming/Carperon/Source/Carp/../Carp/Classes.hpp:59)
#5 00416219 Carp::WinBag::update(this=0x2857f8, o=false) (Z:\CPP Programming\Carperon\Source\Carp\Interface.cpp:60)
#6 00419304 Carp::GameUI::checkUpdate(this=0x2857e4) (Z:\CPP Programming\Carperon\Source\Carp\Interface.cpp:240)
#7 00401B7D Carp::GameApp::loopGame(this=0x2801ac) (Z:\CPP Programming\Carperon\main.cpp:35)
#8 00402145 _fu2041___ZSt4cout() (Z:\CPP Programming\Carperon\Source\Application.cpp:25)
#9 004017A9 main() (Z:\CPP Programming\Carperon\main.cpp:6)
BUILD 2:This is the current build, currently causes a compiler error, which gives me the idea that this might be the cause of the problem.
http://pastebin.com/89gCjH5P
Error:
Z:\CPP Programming\Carperon\Source\Carp\Interface.cpp|57|error: no match for 'operator<<' in 'std::operator<< <std::char_traits<char> >((* &(& std::operator<< <std::char_traits<char> >((* &(& std::operator<< <std::char_traits<char> >((* &(& std::operator<< <std::char_traits<char> >((* & std::cout), ((const char*)"Item Info: ")))->std::basic_ostream<_CharT, _Traits>::operator<< <char, std::char_traits<char> >(a)), ((const char*)"\012ItemContainer: ")))->std::basic_ostream<_CharT, _Traits>::operator<< <char, std::char_traits<char> >(((const void*)((Carp::WinBag*)t|
When I call the getter function given in Character, What is actually happening? I am failing to see what the problem is here, and previous Q&As that I have found do not solve the problem, they only cause it to break another random function later on.
The best I can call this situation is a Heisenbug, since this only occurs when I am in DEBUG mode for an unrelated SEGFAULT somewhere else in the program.
The only possible help I have found is using const-correctness with my getters, only to bring the same exact SEGFAULT to the board again (wasting time into compiling).
P.S. My program has static linkage to Ogre3D, which causes me to have an average compiling time of 5 minutes (more than 7 if I change specific headers). So it will take a long time for me to post edits/results.
P.S. Carp::WinBag is the same as Carp::Interface given in the sample code (gave the wrong class name)
Extra Note: I have had this problem occur for 5 days straight on and off. My sanity can only take so much more of this...
SOLUTION: My situation has been caused from my own laziness somewhere else in the code:
ItemPtr temp(new Item(*listItem[1].get()));
temp->spawnDrop(Coord3(fRAND(-1,1),2,fRAND(-1,1)));
dropList.push_back(temp);
temp.reset(new Item(*listItem[2].get()));
temp->spawnDrop(Coord3(fRAND(-1,1),2,fRAND(-1,1)));
dropList.push_back(temp);
temp.reset(new Item(*listItem[3].get()));
temp->spawnDrop(Coord3(fRAND(-1,1),2,fRAND(-1,1)));
dropList.push_back(temp);
With this, I created a pointer to a new object, BUT at the same time caused the old one to be lost (Memory leak anyone?). This caused all the problems I had later in the code, and writing this the RIGHT way will fix it.
I cannot believe that I did this again after such a long time, and worse NOT realize it... For anyone else that is unfortunate enough to assume this works please DON'T. It will cause endless and confusing stress for you :*
Character doesn't make any guarantee that Items has been initialized to a pointer. When you call it, it simply returns a pointer. If that pointer has not been initialized (or has been initialized to a bad memory location), trying to access that pointer may cause a seg fault:
Character c;
Intem* items = c._items();//get uninitialized ptr in c
items[foo];//seg fault (maybe)
Of course, this isn't the only way that you can get a seg-fault in the call.
What is actually happening in your getter call is that you are taking a "this" pointer, applying an offset to the "this" pointer to find the "items" pointer, and returning that value. However, if your "this" pointer is invalid, then you can get a seg fault. So:
Character* c;//not inititialized
c->_items();//seg fault (maybe)
Can cause a seg fault all on its own.
However, seg faults don't always happen: if the pointer location happens to be to good memory you'll not see the seg fault, you'll just continue down into undefined behavior mode.
SO how on earth do you debug these things? Gotta admit, its a pain in the ass. It is one of the primary reasons people dislike C and C++, and I don't think most people here are going to go looking for it for you.
Most compilers in Debug mode will force uninitialized pointers to a value. Sometimes the value is in hexspeak (My favorite being 0xBADF00D). So look at your pointer values. Visual studio initializes pointers to 0xccccccccccccc.
However, the BEST way to avoid this type of problem is to make having uninitialized pointers impossible. Use vectors and references. When you have to use pointers, stick to smart pointers. Use an RAIIdesign patterns with your constructors and destructors. Follow the Rule of 3 (or Rule of 3-5 in c++11). You'll never (ok you'll "rarely") need to look for invalid values because you've made them hard to exist.

How to track a invalid pointer in C++?

I have my code ready to run with PROOF.
Whenever I run code standalone I works fine, when I activate PROOF, my code crash with a Segmentation Fault.
With GDB I'm able to know exactly where it crashes: when I try to follow a pointer to a object. This makes me think that this pointer (that I'm absolutely sure it was valid before) is invalid and I have no idea why so.
Are there other options? can I track that pointer so I know where it was released?
Use valgrind memcheck tool with --leak-check=summary --track-origins=yes.
This shows invalid memory access (Segmentation Fault) and where they had been freed.

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