Skip to content

Instantly share code, notes, and snippets.

@Masklyne
Created September 12, 2023 22:30
Show Gist options
  • Save Masklyne/291659a570a1accd09df2f9be262f7a2 to your computer and use it in GitHub Desktop.
Save Masklyne/291659a570a1accd09df2f9be262f7a2 to your computer and use it in GitHub Desktop.
strncpy
Use strncpy instead of strcpy: The strncpy function copies a specified number of characters from the source string to the destination buffer, ensuring that it does not write more than the buffer size. However, strncpy has some limitations and may not always behave as expected. It does not guarantee null termination if the source string is longer than the specified number of characters, which can lead to unexpected behavior. To ensure null termination, it is recommended to manually add a null character to the destination buffer after using strncpy.
Use strlcpy or strlcat: The strlcpy and strlcat functions are safer alternatives to strcpy and strcat respectively. They take an additional parameter specifying the size of the destination buffer and ensure that no more than the specified number of characters are copied or concatenated. These functions always null-terminate the destination buffer to prevent buffer overflows. However, it is important to note that strlcpy and strlcat are not standard C library functions and may not be available on all platforms. They are part of the BSD C library and can be used on BSD-based systems or with the libbsd library.
Use safer string handling functions: Instead of using strcpy, consider using safer string handling functions such as strncpy_s or strcpy_s which are part of the C11 standard. These functions perform automatic bounds checking and ensure that the destination buffer is not overflowed. They require an additional parameter specifying the size of the destination buffer to prevent buffer overflows. However, it is important to note that these functions are not available in all C libraries or platforms.
Perform manual bounds checking: If none of the above options are available, you can manually perform bounds checking before using strcpy. Ensure that the destination buffer has enough space to accommodate the source string, taking into account the null terminator. Use functions like strlen to determine the length of the source string and compare it with the size of the destination buffer to avoid buffer overflows.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment