C Safe Functions
In the C language, to improve code safety, especially to prevent common security issues such as buffer overflow, the C11 standard introduced somesafe functions, also known as Annex K standard library functions. These safe functions are mainly enhanced versions of standard string and memory manipulation functions, providing better error detection and handling by adding parameters (such as buffer size).
Features of safe functions:
- Buffer size checking: All safe functions require passing the size of the destination buffer as a parameter to prevent buffer overflow.
- Check the return value: Most functions return an
errno_ttype of error code, which can be used to check whether the function executed successfully. - Better error handling: When the buffer size is insufficient or other problems occur, these functions return an error code and attempt to clear or initialize the output buffer.
Safe functions are well supported in compilers such as Visual Studio, but may not be available in some older compilers, so compatibility needs attention.
The following is a comparison of common safe functions in C and their corresponding traditional functions:
1. String manipulation safe functions
strcpy_s: A safe version of strcpy, which copies a string and checks the destination buffer size.
errno_t strcpy_s(char *dest, rsize_t destsz, const char *src);
strcat_s: A safe version of strcat, which appends the source string to the end of the destination string and checks the buffer size.
errno_t strcat_s(char *dest, rsize_t destsz, const char *src);
strncpy_s: A safe version of strncpy, which copies at most n characters and checks the buffer size.
errno_t strncpy_s(char *dest, rsize_t destsz, const char *src, rsize_t count);
strncat_s: A safe version of strncat, which appends at most n characters to the end of the destination string and checks the buffer size.
errno_t strncat_s(char *dest, rsize_t destsz, const char *src, rsize_t count);
strtok_s: A safe version of strtok, which introduces a context parameter to solve thread-safety issues.
char *strtok_s(char *str, const char *delim, char **context);
2. Formatted output safe functions
sprintf_s: A safe version of sprintf, which checks the buffer size when formatting output to a string.
int sprintf_s(char *buffer, rsize_t buffer_size, const char *format, ...);
snprintf_s: A safe version of snprintf, which limits the number of characters and checks the buffer size when formatting output.
int snprintf_s(char *buffer, rsize_t buffer_size, const char *format, ...);
vsprintf_s: A safe version of vsprintf, which accepts a va_list argument list and checks the buffer size.
int vsprintf_s(char *buffer, rsize_t buffer_size, const char *format, va_list argptr);
3. Memory manipulation safe functions
memcpy_s: A safe version of memcpy, which checks the destination buffer size when copying a memory region.
errno_t memcpy_s(void *dest, rsize_t destsz, const void *src, rsize_t count);
memmove_s: A safe version of memmove, which copies a memory region (allowing overlap) and checks the destination buffer size.
errno_t memmove_s(void *dest, rsize_t destsz, const void *src, rsize_t count);
memset_s: A safe version of memset, which fills a memory block with a specified character and checks the buffer size.
errno_t memset_s(void *dest, rsize_t destsz, int ch, rsize_t count);
4. Other commonly used safe functions
_itoa_s and _ultoa_s: Safe versions of integer conversion functions, which check the destination buffer size when converting integers to strings.
errno_t _itoa_s(int value, char *buffer, size_t buffer_size, int radix);
errno_t _ultoa_s(unsigned long value, char *buffer, size_t buffer_size, int radix);
_strlwr_s and _strupr_s: Safe versions for converting strings to lowercase or uppercase.
errno_t _strlwr_s(char *str, size_t numberOfElements);
errno_t _strupr_s(char *str, size_t numberOfElements);
Example
The following are examples of using C safe functions for string and memory manipulation, showing how they avoid common buffer overflow problems and provide a safer programming approach.
Example 1: strcpy_s and strcat_s
Example
#include
#include
int
main
(
)
{
char
dest
[
20
]
;
// The destination buffer size is 20
const
char
src
=
"Hello, World!"
;
// Use strcpy_s to copy src to dest
if
(
strcpy_s
(
dest
,
sizeof
(
dest
)
,
src
)
!=
0
)
{
printf
(
"strcpy_s failed!\n"
)
;
return
1
;
// Return the error code
}
else
{
printf
(
"After strcpy_s: %s\n"
,
dest
)
;
}
// Use strcat_s to append " C Language" to dest
const
char
appendStr
=
" C Language"
;
if
(
strcat_s
(
dest
,
sizeof
(
dest
)
,
appendStr
)
!=
0
)
{
printf
(
"strcat_s failed!\n"
)
;
return
1
;
// Return the error code
}
else
{
printf
(
"After strcat_s: %s\n"
,
dest
)
;
}
return
0
;
}
Output:
After strcpy_s: Hello, World!
strcat_s failed!
In the above code, strcpy_s successfully copies the string "Hello, World!" to dest, but since the size of dest is 20, it is not enough to hold "Hello, World! C Language", so strcat_s detects the insufficient buffer and returns an error code.
Example 2: memcpy_s
Example
#include
#include
int
main
(
)
{
char
src
[
]
=
"Sensitive Data"
;
char
dest
[
15
]
;
// The destination buffer size is 15
// Use memcpy_s to copy data to dest
if
(
memcpy_s
(
dest
,
sizeof
(
dest
)
,
src
,
strlen
(
src
)
1
)
!=
0
)
{
printf
(
"memcpy_s failed!\n"
)
;
return
1
;
// Return the error code
}
else
{
printf
(
"After memcpy_s: %s\n"
,
dest
)
;
}
return
0
;
}
Output:
After memcpy_s: Sensitive Data
In this example, memcpy_s checks whether the destination buffer dest is large enough to hold the data from src, including the null character at the end of the string. If destsz is less than strlen(src) + 1, the function returns an error and does not perform the memory copy.
Example 3: strtok_s
Example
#include
#include
int
main
(
)
{
char
str
[
]
=
"apple,orange,banana"
;
char
token
;
char
context
=
NULL
;
// Use strtok_s to split a string
token
=
strtok_s
(
str
,
","
,
&
context
)
;
while
(
token
!=
NULL
)
{
printf
(
"Token: %s\n"
,
token
)
;
token
=
strtok_s
(
NULL
,
","
,
&
context
)
;
}
return
0
;
}
Output:
Token: apple
Token: orange
Token: banana
In this example, strtok_s uses the context parameter to save context information when splitting a string, thus avoiding the thread-unsafety issue of strtok.
Example 4: sprintf_s
Example
#include
int
main
(
)
{
char
buffer
[
50
]
;
int
num
=
42
;
const
char
str
=
"Hello"
;
// Use sprintf_s to format a string and check the buffer size
if
(
sprintf_s
(
buffer
,
sizeof
(
buffer
)
,
"Number: %d, String: %s"
,
num
,
str
)
<
0
)
{
printf
("sprintf_s failed!\n"
)
;
return
1
;
// Return the error code
}
else
{
printf
(
"Formatted String: %s\n"
,
buffer
)
;
}
return
0
;
}
Output:
Formatted String: Number: 42, String: Hello
Here, when sprintf_s formats a string, it accepts the buffer size as a parameter. If the formatted string exceeds the size of buffer, the function returns an error, thus avoiding buffer overflow.
The above examples demonstrate the use of C safe functions for string copying, concatenation, memory copying, string splitting, and formatted output. These functions provide buffer size checking, significantly improving code safety.
Reference manual
Safe functions are mainly intended to prevent buffer overflow (Buffer Overflow), a type of vulnerability that usually arises when functions do not check the size of the destination buffer.
Currently, mainstream safe function standards mainly come from Annex K (bounds-checking interfaces) of the C11 standard, as well as enhanced versions provided by various operating systems (such as the MSVC CRT on Windows).
The table below shows a reference table of C safe functions.
1. String handling
This is the area most prone to overflow; safe functions usually require passing the size of the destination buffer.
| Original function (unsafe) | Safe replacement function | Main improvements |
|---|---|---|
strcpy |
strcpy_s |
Adds a destination buffer size parameter; if the source string is too long, a constraint handler is invoked. |
strcat |
strcat_s |
Adds a parameter for the remaining size of the destination buffer to prevent out-of-bounds access during concatenation. |
strncpy |
strncpy_s |
Ensures that the destination string ends with \0 a null terminator, and adds runtime error checking. |
strtok |
strtok_s |
Introduces a context pointer (Context), making itThread Safetyand more robust. |
strlen |
strnlen_s |
Adds a maximum check length to prevent infinite loops in bad data that lacks a \0 null terminator. |
2. Formatted input/output
Unsafe formatting functions may lead to format string vulnerabilities or buffer overflow.
| Original function (unsafe) | Safe replacement function | Main improvements |
|---|---|---|
sprintf |
snprintf / sprintf_s |
snprintf Limits the number of characters written;sprintf_s Checks the validity of the format string. |
vsprintf |
vsnprintf_s |
Adds a buffer size limit, applicable to variable argument lists. |
scanf |
scanf_s |
locks %s and %c and other conversion specifiers,forcesrequiring a buffer size to be provided. |
fscanf |
fscanf_s |
Adds a length limit when reading file input. |
sscanf |
sscanf_s |
Adds a length limit when reading from a string. |
3. Standard input/output
| Original function (unsafe) | Safe replacement function | Main improvements |
|---|---|---|
gets |
gets_s / fgets |
gets has been deprecated in C11.gets_s A read limit must be specified. |
tmpnam |
tmpnam_s |
Adds a check on the size of the buffer for generating temporary file names. |
4. Memory manipulation
| Original function (unsafe) | Safe replacement function | Main improvements |
|---|---|---|
memcpy |
memcpy_s |
Adds a destination buffer size check. If overlap or overflow occurs, an error is returned. |
memmove |
memmove_s |
Adds a size limit check when handling overlapping memory regions. |
memset |
memset_s |
Ensures that the compiler does not skip the memory-clearing operation due to optimization (often used to clear sensitive data such as passwords). |