Common Programming Mistakes
From Globulation2
Here is a list of take special care when coding in C/C++:
- Buffer overflow in C strings. Imagine you have the following C string:
- char nick[16];
- Now imagine you want to add an _ to nick that are already in use. A naive code would be:
- if (nick_already_in_use) strcat(nick, "_");
- This code is wrong because it can leads to a buffer overflow if strlen(nick) = 15. So the correct code is:
- if (nick_already_in_use && strlen(nick) < 15) strcat(nick, "_").
- A = B assigns the value of B to A. = is an assignation operators.
- A == B returns true if A is equal to B and false otherwise. == is a comparaison operator.
- Take care of function with side effects:
- For instance, strtok is such a function. The following declaration char *diffusion = strtok(NULL, " =");, even if diffusion is not used, does modify the string previously passed to strtok. Removing it can lead to a bug.