2

I have a simple for-loop in C++ and the initialization statement is:

for (int n = 0; n < this->fileLines.size(); n++) {

For some crazy reason, the value of n is being set not to 0 but to 249758, which causes the for-loop to evaluate wrong.

Any ideas why this is initializing wrong (i.e., not to 0)?

enter image description here

2
  • Are you building in debug or release mode? oftain release mode cannot give you correct values when you peek at variable values due to optimization. Commented Dec 12, 2012 at 18:25
  • 1
    It looks like you've stopped just before n is initialised. What happens if you step forward by one instruction? Commented Dec 12, 2012 at 18:30

2 Answers 2

6

I think you need to verify after the for loop what the value of n is, I don't see any way this could non-0. Check the value at the start of the switch. Your breakpoint may have interrupted before n was actually set.

Sign up to request clarification or add additional context in comments.

4 Comments

Agreed. The screenshot shows that the line n = 0; is about to execute, but hasn't yet.
the switch never executes... if you put a breakpoint in the switch, it is never triggered. The loop never occurs because n > size()
What is the value of this->fileLines.size()?
After a lot of playing around, what seems to have happened is as follows: (1) I was getting confused by the debugger. n seems to have been declared but not initialized and (2) it would never be initialized because as @jeremy pointed out correctly, the variable value was never greater than 0; The lesson: thoroughly unit test your code.
0

Have you tried sticking

std::cerr<<n<<std::endl;

inside of the for loop? This seems a more direct way of observing the value during the running of the program to verify whether or not it is doing what you think, and optimization will not give you problems with this output.

Perhaps your program is multithreaded and someone is inappropriately writing to that memory location?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.