Reputation: 1356
I have this loop that parses machine code and emulates the instructions as if it were a processor. If at any point I try to access a memory location that is beyond what the program defines as the size of memory (1MB), it will print an error saying that I'm out of range.
This is a school assignment, so all of the input binaries should work correctly if my code is correct. But on one of the binaries, I have an error stating that I'm trying to access memory outside this range. So I want to put an fprintf()
(or just printf()
, it doesn't matter) statement in there to see the contents of some of my variables. However, when I do this, I get completely different behavior. I never get this message and instead the program loops infinitely. I'm not changing anything else. And it seems that it doesn't matter what I print. Inserting printf("hello")
causes the same behavior.
If I put my fprintf()
inside the function that prints the error, I don't get the infinite loop and everything prints as I would expect.
It's a fairly large and complex program, so I can't just paste it in here and I don't think just a small portion will suffice, so I hope I've provided enough information to get help.
I am putting newlines at the end of my statements as I've read that is supposed to flush the buffer, but even if I add fflush(stdout)
, it doesn't seem to matter.
Upvotes: 0
Views: 380
Reputation: 993153
With the information you've been able to supply, it sounds like your program is exhibiting undefined behaviour. Undefined behaviour doesn't necessarily mean that the program will crash, it could appear to work correctly. Until you change something else, like adding an fprintf()
somewhere, then it might fail.
You might want to try running your program under Valgrind to help catch memory-related errors. Also, turn up the warning level on your compiler all the way and fix everything it finds.
Static analysers such as Cppcheck and the Clang Static Analyzer are also helpful.
Upvotes: 1