Which functions in the C standard library commonly encourage bad practice? [closed]
Solution 1:
What C standard library functions are used inappropriately/in ways that may cause/lead to security problems/code defects/inefficiencies ?
I'm gonna go with the obvious :
char *gets(char *s);
With its remarkable particularity that it's simply impossible to use it appropriately.
Solution 2:
A common pitfall with the strtok()
function is to assume that the parsed string is left unchanged, while it actually replaces the separator character with '\0'
.
Also, strtok()
is used by making subsequent calls to it, until the entire string is tokenized. Some library implementations store strtok()
's internal status in a global variable, which may induce some nasty suprises, if strtok()
is called from multiple threads at the same time.
The CERT C Secure Coding Standard lists many of these pitfalls you asked about.
Solution 3:
In almost all cases, atoi()
should not be used (this also applies to atof()
, atol()
and atoll()
).
This is because these functions do not detect out-of-range errors at all - the standard simply says "If the value of the result cannot be represented, the behavior is undefined.". So the only time they can be safely used is if you can prove that the input will certainly be within range (for example, if you pass a string of length 4 or less to atoi()
, it cannot be out of range).
Instead, use one of the strtol()
family of functions.