c++ having strange problem - c++

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.

Related

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);
}
}

NVIDIA Cuda if-statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a very strange error. I am writing a program in Cuda that emulates the Conway Game of Life. I transfered the 2D array to device and there is a if-case that check for the state's thread.
if(iam==-1)
{ //i am on
iam=0;
}
else if(iam==1)
{ //i am dying
iam=-1;
}
else //i am off
{
if(counter_alive==2)//two neighboors alive
{
iam=1; //i will be on
}
// iam = -999;
}
When the last line is in comment nothing works and the var "iam" has the first value. But if i drop the //, it will work. Of course, if the flow's code execute the else, the var "iam" will take the value -999.
Any ideas? Have i missed something?
Thanks in advance!
You do not show the initial value of the variable iam or counter_alive. Let us assume that the compiler has set it to 0. Of course even if the compiler just sets the space to a random value, this analysis would be the same.
if(iam==-1)
{ //i am on
iam=0;
}
Since the initial value is 0, then this fails and drops through
else if(iam==1)
{ //i am dying
iam=-1;
}
Again, since the initial value is 0, then it fails and drops through.
else //i am off
{
if(counter_alive==2)//two neighboors alive
{
iam=1; //i will be on
}
// iam = -999;
}
It enters here with a value of 0. However, since counter_alive has never been set, it is also 0 and the if fails.
Thus, the iam variable is never changed from 0. Note that since neither of the critical values changes, iam will never be reset from 0. If you uncomment the last line, it will always be explicitly set to -999 and will never change either. That is because you never test for 0 or 999. If you had it as -1 it would change to 0 and then never change unless you change counter_alive somewhere else to be 2.
Note that Explanation of CUDA C and C++ explains how the looping is handled as parallel processing. In that case, the reaction of the various items in the array may not be what you would expect in plain C (single stream) processing.

Where to look for Segmentation fault?

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.

C++ File outputting strange number, and part of code not running

Yeah. So, I'm trying to make a code for a guessing game. In this game, there's a hard mode. In hard mode, you have 15 guesses, and have to guess between 1 and 500. But my problem is this:
I'm trying to have hard mode save & display your wins/losses, but when it outputs the contents of wins.txt it outputs something like this:
Wins: 0x7fffee26df78
Losses: 0x7fffee26e178
It's really confusing me. Here's the part of the code I have for that:
ifstream losses_var("losses.txt");
ifstream wins_var("wins.txt");
losses_var>> loss;
wins_var>> win;
wins_var.close();
losses_var.close();
Then it gets called with:
cout<<"Wins: "<< wins <<"\nLosses: "<< losses <<"\n"
If you would like to see the full source code, it's here: http://pastebin.com/gPT37uBJ
My second problem:
Hard mode won't display when you win. That's pretty much the whole problem. In my code, the loop for asking users for input uses
while (guess != randNum)
So at the end bracket I have what I want the code to display when a user wins, but it just doesn't run. It just stops. I would like it if someone could help me with this. The line that has the bug is line 97 through 105. Again, source code is here: http://pastebin.com/gPT37uBJ
You've got your variable names confused
cout<<"Wins: "<< wins <<"\nLosses: "<< losses <<"\n";
should be
cout<<"Wins: "<< win <<"\nLosses: "<< loss <<"\n";
It's important to pick good variable names. One reason is so that you don't confuse yourself about what your variables mean (if you confuse yourself think how it's going to be for someone else looking at your code).
Others have already answered the output problem (win vs. wins). The other problem is probably in your logic of while loop nesting. The outer loop (while (guess != randNum)) starts, but its body contains the entire inner loop (while (guesses_left != 0)). This means that the outer condition is not checked again until the inner loop terminates, which means you've run out of guesses. Also note that if you guess correctly, inner loop will never terminate. You probably want something like this:
while (guesses_left > 0) {
// input user's guess
if (guess < randNum) {
// process it
} else if (guess > randNum) {
// process it
} else {
// it's equal, user won
// do what's necessary for a win
return 0;
}
}
// ran out of guesses
// do what's necessary for a loss
return 0;
You are not writing your variables win and loss to cout. From your pasted code, I can see that wins and losses are ofstream objects, which means you are probably seeing addresses there. I would advise you to choose more informative variable names to avoid hard to spot mistakes like this.

Break and rerun while loop c++ Windows

I'm a rookie programmer, so please be polite.
Well i'm trying to write a simple Terminal Backgammon game, just for fun, but i have a problem.
The entire game runs in a while loop which keeps re running as long as nobody moved all their bricks to the end of the board.
A simple integer controls whatever it is black or white who plays.
I wrote a function to check for any possible moves, cause i want to program to skip the turn in case absolutely no moves can be made.
Well, i want this function to run and in case it returns false(No possible moves) then i want the rest of the code to skip and change the turn to the next player. For example if the dice combination gives no possible moves for black, then i want the program to skip black and go to white.
So i sort of want to break the rest of the while loop, but keep it running.
It's a little complicated for me to explain the issue, but i hope you guys understand.
Thanks alot
- Martin
It sounds like you want to use continue:
while (someCondition)
{
doSomething();
if (someOtherCondition)
continue;
doSomethingElse();
}
In this example, if someOtherCondition is true, the continue statement will cause the program to jump back to the top of the loop rather than continuing to execute the following statements. If someOtherCondition is false, doSomethingElse() will get run as normal.
I think this is roughly what you want to know.
Hope it helps.
while( keepRunning )
{
bool noPossibleMoves = checkForPossibleMoves();
setup for each loop iteration
Do things here that are always necessary.
if( noPossibleMoves )
{
continue; // This will go to the top of the while loop
}
wait for user input etc...
...
...
}