Coding Standards
Unsafe String Functions
C.3 Unsafe String Functions
A few of the string functions declared in the standard ‘<string.h>’ and ‘<stdio.h>’ headers
are notoriously unsafe. The worst offenders are intentionally not included in the Pintos C
library:
•
strcpy()
When used carelessly this function can overflow the buffer reserved for its output string. Use strlcpy() instead. Refer to comments in its source code in
lib/string.c for documentation.
•
strncpy()
This function can leave its destination buffer without a null string terminator.
It also has performance problems. Again, use strlcpy().
•
strcat() Same issue as strcpy(). Use strlcat() instead. Again, refer to comments in
its source code in lib/string.c for documentation.
•
strncat()
The meaning of its buffer size argument is surprising. Again, use strlcat().
•
strtok() Uses global data, so it is unsafe in threaded programs such as kernels. Use
strtok_r() instead, and see its source code in lib/string.c for documentation and an example.
•
sprintf()
Same issue as strcpy(). Use snprintf() instead. Refer to comments in
lib/stdio.h for documentation.
•
vsprintf()
Same issue as strcpy(). Use vsnprintf() instead.
If you try to use any of these functions, the error message will give you a hint by referring
to an identifier like dont_use_sprintf_use_snprintf.