Where to look for Segmentation fault? - c++

My program only sometimes gets a Segmentation fault: 11 and I can't figure it out for the life of me. I don't know a whole lot in the realm of C++ and pointers, so what kinds of things should I be looking for?
I know it might have to do with some function pointers I'm using.
My question is what kinds of things produce Segmentation faults? I'm desperately lost on this and I have looked through all the code I thought could cause this.
The debugger I'm using is lldb and it shows the error being in this code segment:
void Player::update() {
// if there is a smooth animation waiting, do this one
if (queue_animation != NULL) {
// once current animation is done,
// switch it with the queue animation and make the queue NULL again
if (current_animation->Finished()) {
current_animation = queue_animation;
queue_animation = NULL;
}
}
current_animation->update(); // <-- debug says program halts on this line
game_object::update();
}
current_animation and queue_animation are both pointers of class Animation.
Also to note, within Animation::update() is a function pointer that gets passed to Animation in the constructor.
If you need to see all of the code, it's over here.
EDIT:
I changed the code to use a bool:
void Player::update() {
// if there is a smooth animation waiting, do this one
if (is_queue_animation) {
// once current animation is done,
// switch it with the queue animation and make the queue NULL again
if (current_animation->Finished()) {
current_animation = queue_animation;
is_queue_animation = false;
}
}
current_animation->update();
game_object::update();
}
It didn't help anything because I still sometimes get a Segmentation fault.
EDIT 2:
Modified code to this:
void Player::update() {
// if there is a smooth animation waiting, do this one
if (is_queue_animation) {
std::cout << "queue" << std::endl;
// once current animation is done,
// switch it with the queue animation and make the queue NULL again
if (current_animation->Finished()) {
if (queue_animation != NULL) // make sure this is never NULL
current_animation = queue_animation;
is_queue_animation = false;
}
}
current_animation->update();
game_object::update();
}
Just to see when this function would output without any user input. Every time I got a Segmentation fault this would output twice right before the fault. This is my debug output:
* thread #1: tid = 0x1421bd4, 0x0000000000000000, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
frame #0: 0x0000000000000000
error: memory read failed for 0x0

Some causes of segmentation fault:
You dereference a pointer that is uninitialized or that points to NULL
You dereference a deleted pointer
You write outside the bounds of the scope of allocated memory (e.g. after the last element of an array)

Run valgrind with your software (warning, it really slows things down). Its likely that memory has been overwritten in some way. Valgrind (and other tools) can help track down some of these kinds of issues, but not everything.
If its a large program, this could get very difficult as everything is suspect since anything can corrupt anything in memory. You might try to minimize the code paths run by limiting the program in some way and see if you can make the problem happen. This can help reduce the amount of suspect code.
If you have a previous version of the code that didn't have the problem, see if you can revert back to that and then look to see what changed. If you are using git, it has a way to bisect search into the revision where a failure first occurred.
Warning, this kind of thing is the bane of C/C++ developers, which is one of the reason that languages such as Java are "safer".
You might just start looking through the code and see if you can find things that look suspicious, including possible race conditions. Hopefully this won't take to much time. I don't want to freak you out, but these kinds of bugs can be some of the most difficult to track down.

Related

Exception thrown: read access violation. std::shared_ptr<>::operator-><,0>(...)->**** was 0xFFFFFFFFFFFFFFE7

Good afternoon to all! I am writing a game engine using OpenGL + Win32 / GLFW. Therefore, I will say the project is large, but I have a problem that has led me to a dead end and I can't understand what the problem is. The problem is that I have a shared_ptr<Context> in the 'windows' class (it is platform-based) that is responsible for the context (GL, D3D). And everything works fine when I launch the application, everything is drawn normally, but when I start entering the cursor into the window, a crash occurs when any function calls from context, in my case is:
context->swapBuffers();
Here a crash:
std::shared_ptr<Context>::operator-><Context,0>(...)->**** was 0xFFFFFFFFFFFFFFE7.
Then I got into the callstack and saw that the context-> itself is non-zero, so the function should be called.
Then I searched for a long time for the problem and found that when I remove the Win32 message processing code, and when I remove it, errors do not occur when calling a function from context->. I removed everything unnecessary from the loop and left only the basic functions and tried to run it like this, because I thought that some other functions inside were causing this problem, but no.
while (PeekMessageW(&msg, NULL, NULL, NULL, PM_REMOVE) > 0) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
That is, when I delete TranslateMessage() and DispatchMessage(), the error goes away. And then I finally got confused i.e I don't understand what is happening. And then I thought that maybe somehow the operating system itself affects that pointer, prohibits reading or something like that.
And then I paid attention to __vtptr in the call stack, and noticed that it is nullptr, and moreover it has the void** type. And also the strangest thing is that in the error I have ->**** was 0xffffffffffffffc7 as many as four consecutive pointers. What is it?
I understand I practically didn't throw off the code, because I have a big project and I think it doesn't make sense to throw everything, so I tried to explain the problem by roughly showing what is happening in my code. I will be grateful to everyone who will help :)

C++ Debug Assert Error / Crash (While Loop)

I'm debugging a very old application (Visual C++ 6) due to a crash. I have isolated the crash into a while loop. This app reads a bunch of strings from a database and outputs them into a file for processing.
This while loop appears to be looping through all strings retrieved from the DB and wrapping them in a delimiter/end character. However, the while loop will randomly crash.
I have a particular set of data containing around 2000 strings, and at some point, during processing, the loop will crash (or give a debug assertion error in debug mode).
What's strange is that this loop does not stop in the same location each time (bad string was my first thought), nor is this a common occurrence. This app has processed hundreds of thousands of rows over the years, and yet it chokes on this particular data set somewhat randomly.
I added some logging code initially (which I've stripped out, and it appears that the crash is occurring on the actual execution/evaluation of the WHILE line.
Is there anything, in particular, I should look for? I was thinking perhaps this is an index out of bounds error, but I would think it would happen consistently in the same spot with the same data set if that were the case. Does anyone see anything with this code I should double-check, or can offer any advice on how to better troubleshoot this?
//Definitions
CStringList m_stlMessageList;
CStringList m_stlMessageIDList;
//Populating list
rec.Open(CRecordset::forwardOnly, strSQL);
while (!rec.IsEOF())
{
rec.GetFieldValue("string_id", strMessageID);
strMessageID.TrimRight();
rec.GetFieldValue("string_text", strMessage);
strMessage.TrimRight();
rec.GetFieldValue("string_destination", strDestination);
strDestination.TrimRight();
rec.GetFieldValue("string_ip", strIP);
strIP.TrimRight();
//Add to the Lists...
m_stlMessageIDList.AddTail(strMessageID);
m_stlMessageList.AddTail(strMessage);
rec.MoveNext();
}
//Code thats crashing.
CString strSegment, strTemp, strTmp;
BOOL bFirst = TRUE;
POSITION POS = m_stlMessageList.GetHeadPosition();
while (POS)
{
strSegment = m_stlMessageList.GetNext(POS);
strTemp = strSegment.Left(4);
strSegment.Format(strSegment + "%c", 13);
if (POS)
{
strTmp = m_stlMessageList.GetPrev(POS);
m_stlMessageList.SetAt(POS, strSegment);
strTmp = m_stlMessageList.GetNext(POS);
}
else
{
m_stlMessageList.RemoveTail();
m_stlMessageList.AddTail(strSegment);
}
}

Why does my C++ program crash with exit code 11 when I remove a cout statement?

In my C++ project, I encounter a very strange issue. It crashes with exit code 11 when I remove a certain log statement (cout).
This answer points to a source that explains exit code 11 (actually EAGAIN) with the following statement:
The system lacked the necessary resources to create another thread, or
the system-imposed limit on the total number of threads in a process
PTHREAD_THREADS_MAX would be exceeded.
But I am pretty sure don't create any additional threads in my code (at least not explicitly). So why does the error occur and why does it go away when I use the log statement?
For reference, I will post the code but it's of course completely out of context and basically the only relevant line is the one with the log statement.
PayloadRegionMapper(string mappingTechniqueName, string configPath = "")
: payload(PAYLOAD), config(Config(configPath)) {
cout << "construct PayloadRegionMapper" << endl; // if commented out, my program crashes....
frames = generateFrames();
setMappingTechnique(mappingTechniqueName);
}
Run the program using a debugger and then backtrace once the crash happens.
Using the bt and frame command you can get an idea about the behaviour of the program during the crashing situation.
gdb <executable>
.....<crash happened>
bt
<It will give you the stack frame >
frame <frame number>
Then look for the values and memory area there.

c++ having strange problem

I have a function that creates and insert some numbers in a vector.
if(Enemy2.dEnemy==true)
{
pt.y=4;
pt.x=90;
pt2.y=4;
pt2.x=125;
for(int i=0; i<6; i++)
{
Enemy2.vS1Enemy.push_back(pt);
Enemy2.vS2Enemy.push_back(pt2);
y-=70;
pt.y=y;
pt2.y=y;
}
Enemy2.dEnemy=false;
Enemy3.cEnemy=0;
}
It should insert 6 numbers in two vectors, the only problem is that it doesn't - it actually inserts more.
I don't think the snippet will run unless Enemy2.dEnemy == true, and it won't stay true for ever.
The first time the snippet runs, then Enemy2.dEnemy is set to false and it shouldn't run again.
I don't set Enemy2.dEnemy to true anywhere except when the window is created.
If I insert a break point any where in the snippet, the program will work fine - it will insert ONLY 6 numbers in the two vectors.
Any ideas what's wrong here?
ok so i did some debugging.
i found that Enemy2.dEnemy=false; is being skipped for some reason.
i tried to do this to see if it was.
if(Enemy2.dEnemy)
{
pt.y=4;
pt.x=90;
pt2.y=4;
pt2.x=125;
for(int i=0; i<6; i++)
{
Enemy2.vS1Enemy.push_back(pt);
Enemy2.vS2Enemy.push_back(pt2);
y-=70;
pt.y=y;
pt2.y=y;
}
TCHAR s[244];
Enemy2.dEnemy=false;
if(Enemy2.dEnemy)
{
MessageBox(hWnd, _T("0"), _T(""), MB_OK);
}
else
{
MessageBox(hWnd, _T("1"), _T(""), MB_OK);
}
Enemy3.cEnemy=0;
}
well the message box popped saying 1 and my code worked fine. it seems that Enemy2.dEnemy=false; doesn't have time to run ;/
blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah!
ok i found where is the real problem which was causing to insert more than 6 numbers..
it was where i was asigning Enemy2.dEnemy=true;
if(Enemy2.e1)
{
Enemy2.now=time(NULL);
Enemy2.tEnemy=Enemy2.now+4;
Enemy2.e1=false;
}
if(Enemy2.tEnemy==time(NULL))
{
check=1;
Enemy2.aEnemy=0;
Enemy2.dEnemy=true;
}
the problem seems that the second if runs more than one time, which is weird!
First things first: get rid of that abominable if (Enemy2.dEnemy == true) - it should be:
if (Enemy2.dEnemy)
(I also prefer to name my booleans as a readable sentence segments like Enemy2.isABerserker or Enemy3.hasHadLeftLegCutOffThreeInchesBelowTheKnee but that's just personal preference).
Other than that, the only thing I can suggest is a threading problem. There's nothing wrong with that code per se, but there is a window in which two threads could enter the if statement and both start pushing values into your vector.
In other words, if thread 1 is doing the pushing when thread 2 encounters the if statement, thread 2 will also start pushing values, since thread 1 has yet to set dEnemy to true. And don't think you can just move the assignment to the top of the if block - that will reduce but not remove the window.
My advice is to print out the contents of the vectors in the situation where they have more than six entries and that may give a clue as to what's happened (post the output here if you wish).
Re your update that the second if below is running twice:
if(Enemy2.e1)
{
Enemy2.now=time(NULL);
Enemy2.tEnemy=Enemy2.now+4;
Enemy2.e1=false;
}
if(Enemy2.tEnemy==time(NULL))
{
check=1;
Enemy2.aEnemy=0;
Enemy2.dEnemy=true;
}
If this code is executed twice in the same second (and that's not beyond the bounds of possibility), the second if statement will run twice.
That's because time(NULL) give you the number of seconds since the epoch so, until that second is over, you may well be executing the contents of that if thousands of times (or more).
If this problem disappears when you put in a breakpoint or a diagnostic output message, that's a strong clue that the problem is undefined behavior, which is usually caused by something like dereferencing an uninitialized pointer or careless use of const_cast.
The cause of the problem probably has nothing to do with the code you're looking at. It's caused somewhere else and just happens to show up here. It's like someone being hit by a falling brick: the obvious symptom is a man lying unconscious on the sidewalk, but the real problem has nothing to do with the man or the sidewalk, it's several stories up.
If you want to find the cause of the error, remove your diagnostics until the problem reappears, then start removing everything else. Prune away all of the other code. Whenever the error stops, back up until it starts again; if you don't see the cause of the error, start pruning somewhere else. Eventually the bug will have nowhere to hide.

How to find the real problem line in my code with Application Verifier?

I am now trying to use this Application Verifier debugging tool, but i am stuck, first of all: it breaks the program at a line that is simple variable set line (s = 1; for example)
Secondly, now when i run this program under debugger, my program seems to have changed its behaviour: i am drawing image, and now one of the colors has changed o_O, all those parts of the image that i dont draw on, has changed the color to #CDCDCD when it should be #000000, and i already set the default color to zero, still it becomes to #CDCDCD.
How do i make any sense to this?
Here is the output AV gave me:
VERIFIER STOP 00000002: pid 0x8C0: Access violation exception.
14873000 : Invalid address causing the exception
004E422C : Code address executing the invalid access
0012EB08 : Exception record
0012EB24 : Context record
AVRF: Noncontinuable verifier stop 00000002 encountered. Terminating process ...
The program '[2240] test.exe: Native' has exited with code -1073741823 (0xc0000001).
Typically when breakpoints are hit like this (via AV or an unhandled exception, etc.) inside a debugger, there is a green arrow pointing to a line of code. That arrow is pointing to the next statement to execute when the thread returns from the current function. Perhaps this green arrow is pointing to the line where you wrote "s = 1", but really the offending code is the line above it. Now I can't see your code so I can't exactly know for sure and I don't have enough rep to post a comment - but this is something that is easy to check the next time the breakpoint is hit.
I am willing to bet that s is NOT a "simple" variable. I'm much more likely to believe it's something like this:
class Foo;
int s;
void Bar() {
s = 1;
}
};
Sure, it looks like a simple s=1 statement, but in reality it is a this->s=1 statement. And if this is an invalid pointer, this->s isn't a proper variable either.