+ 2
Day of the Week
Itās the strangest thing. Iāve written a program for the Day of the Week code coach, and while it satisfied all the test cases, one date always yields a Seg Fault: March 13, 1887 āorā 3/13/1887 I donāt think any other date has caused this issue. Any ideas about this one? If you too run the program with this date, does it Seg Fault? https://code.sololearn.com/ctlTKkJ5BlvY/?ref=app
3 Answers
+ 3
Line 127: for some reason, day_y ends up being 7. That accesses the 'array' array past its boundaries causing the segmentation fault.
More importantly, helping to help yourself: How did I find this?
Ordinarily, I would run it through a debugger and track the exact line that SIGSEGVs. But my web access doesn't work anymore, so I cannot easily download your code to the PC. Limited in my options, I put marker outputs in your main function:
puts("mark x");
//return 0;
Where x numbers the markers. I did that for every function that is being called, setting and removing the return 0; statement, until I located where your program explodes. Then I examined the problematic function where a SIGSEGV could occur and tested the values (in this case array and day_y, printing day_y and skipping array access)
+ 2
Thanks to your excellent analysis, Ani Jona š, I tracked down the root cause.
Sean It seems any date that would be a Sunday would result in the exception. The loop condition in line 114 is the error origin.
while (day_y > 7) {
day_y -= 7;
}
It should be (day_y >= 7).
You could replace the whole loop with the line:
day_7 %= 7;
+ 2
Ani Jona: Iāve not tried that marker output method before, but Iāll definitely use it next time. Thanks for explaining it!
I took your suggestion, Brian, and replaced the while loop with
day_y %= 7
Thanks a bunch!
It makes perfect sense what was going wrong now: as you both stated, I was allowing the while loop to output ā7ā (an invalid index for my array), when it should have reduced that number to ā0ā.
Thank you both for reviewing my code and bringing that to light!