Function safety

You can avoid some common programming issues by using safer versions of C functions. The following table lists unsafe functions and their safer versions (if available), as well as additional considerations for making some functions safer to use. For more information, refer to C reference documentation like the C Library reference.

Unsafe functions Preferred functions Comments



fgets() reads a string of characters from the stream and stores them in the specified array. Use fgets() instead of gets() because it allows you to specify the length of the buffer to store the string in.



getcwd()  returns the name of the current working directory.  Use getcwd() instead of getwd() because it allows you to specify the size of the buffer where the NULL-terminated name of the current working directory will be placed. The maximum size that might be required for the function's buffer parameter is PATH_MAX + 1 bytes.



This function resolves a path name. If you use realpath(), ensure the function's resolved_path parameter is sufficiently large.

scanf() family of functions


These functions scan formatted input. If you use these functions, do not send data to a buffer without controlling the maximum length of the arguments.

sprintf() and vsprintf()

snprintf() and vsnprintf()

snprintf() and vsnprintf() write formatted output to a character array, up to a given maximum number of characters. Both place a NULL character at the end of the generated character string.

Use snprintf() instead of sprintf() because it has boundary checking. Use vsnprintf() instead of vsprintf() because it checks the length of a string and can help you avoid buffer overruns.

strcpy() and strncpy()

strcat() and strncat()

strlcpy() and strlcat()

strlcpy() copies strings and strlcat() concatenates strings. strlcpy() and strlcat() are designed to be safer, more consistent, and less error-prone replacements for strncpy() and strncat().

strlcpy() and strlcat() take the full size of the buffer (not just the length) and are guaranteed to NULL-terminate the result (as long as the size is larger than 0 or, in the case of strlcat(), as long as there's at least one byte free in the destination string).

The "wide" versions of these functions are also dangerous. wcscpy() does not have an "l" safe version to use. wcsncpy() does not necessarily NULL-terminate the output. You must ensure the output buffer is NULL-terminated.