I am co-teaching a practical session on C for a group of first-year CS students that have just started programming.
It seems that they often respond quite well to a carrot and stick [1] approach, where you point out common mistakes made by new programmers and then offer a solution - or threaten to poke their eyes out if they repeat them (just joking!).
In order to have more examples at my disposal, I have started collecting a list of common snippets of one to three lines that do not behave as an inexperienced programmer would expect. Explaining what really happens seems to give a better understanding of the language, while at the same time saving us from helping the students with the same little mistakes over and over again.
For example, I mentioned the all-time classic assignment-as-condition land-mine [2]:
if (a = b) ...
as well as the more sinister undefined-evaluation-order issue:
func(a, a++);
which always tends to appear when a bunch of new programmers are in their "Wow, look how short this code is!" phase, while still being unaware of little details such as sequence points [3].
What are the most common bugs of this kind that you have encountered in C code?
I am interested in little code snippets that contain practices dangerous for a new programmer or where the bug is obvious to more experienced eyes - not logical errors that should be placed within a significantly larger context.
Especially appreciated would be any references (e.g. mailing-list archive links) to actual bugs of this kind that have been found in open source projects.
func(a, a++)
works the same way no matter what the argument evaluation order is? - MehrdadC/C++
is a programming language! - pmg.c
, right?. Or, possibly even worse, compiling C code with a C++ compiler and then claiming to know C++. - thkalaa++
takes place before or after the firsta
is evaluated. This is an example of Undefined Behavior. - RBerteigint a = 1; printf("%i %i\n", a, a++);
gives2 1
on both my Linux/GCC and my Windows/VS2010 development systems... - thkala