29-Dec-2016

I found the C puzzles webpage by Gowri Kumar to be a very interesting collection of oddities of the C language and some of its basic libraries. If you work with C for fun or profit, I encourage you to go and give them a try. I found very few of them to produce behavior I hadn’t expected, which could be a symptom of overfamiliarity with C. I did find a few surprises though, which I felt warranted further investigation.

Gowri asks “What is the potential problem with the [] program?” (which is hopefully obvious), yet I was actually surprised by the program’s actual behavior when the problem wasn’t encountered, as it seemed to conflict with that earlier puzzle. This conflict is accentuated by removing the read into a buffer [full source]:

Does your explanation hold up to this example’s behavior when called with an argument of 1, 2, and 3? What is this program doing in each of those three cases? If you trace the system calls the program makes with an argument of 1, 2, and 3, does that match the behavior you predicted?
I found all this to be pretty counterintuitive!

Update: Here’s a version which shows more of what’s going on. Try running it with “0”, “1”, and “5”, for example. Or piping the output of “echo 1 2 3 4” to it.