Unfortunately, we cannot debug the issue to the full extent. It seems that the issue is related to the output buffer, therefore some fiddling with flushing helps. For a complete analysis we also need to know how CodeChef judge is organized in regards to input/output streams.
I was not able to replicate the situation on my local environment - gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609. The problem is only reproducible when running on CodeChef judge.
What’s observable - CodeChef judge is definitely more robust with cin/cout IO.
Although fflush(stdout) does seem to make it work, I would not say for sure buffering is the problem, since even after disabling buffering with setbuf(stdout, NULL) the behavior does not change (works with fflush but not without).
Looks like including header causes initialization of the standard C++ streams and their synchronization with the standard C streams. Adding ios_base::sync_with_stdio(false) corrects the issue.
Seeee, it turned out to be undefined behavior after all XD.
@l_returns - For undefined behavior, you really cannot say. Even adding a int aabcdef=1; might have worked and given AC for that case. Perhaps it all depends on what value was in memory accessed out of bounds? I guess that part had a good value
Why it is defined for one library and not defined for other one...
Its not so. Thing is, anything can happen in undefined behavior. Even for same library, things like print statements, new varaibles etc can change stuff. It all depends on what compiler does/make your code while compiling it. It applies some optimizations, does some reordering etc to fasten execution.
@l_returns Didn’t really use anything fancy. Simply went through the code and added some asserts to check the indexing (something I’m very fond of doing even in my own code). At first I thought that maybe there was a problem with the factorial but none of those asserts triggered, ruling out any obvious problems with the factorial. Then I saw the strangely written while-loop, and it was pretty clear what was the problem.
@algmyr So basically, this varies from compiler to compiler as the compilers are not set to produce results for a false(invoking undefined behaviour) code…right?
Behavior may or may not be different in different compilers, or even for the same code snippet in different circumstances using the same compiler. Point is you can’t really assume anything as soon as you introduce UB into the program.
In the case you had, compiling with “-fstack-protector-all -fsanitize=address” and testing against a few cases would probably have showed you that something was wrong. Try running your old code with the flags I mentioned on the case: