Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
strcpy(3) can be safe. Some compilers, such as GCC and Clang, use a feature test macro, _FORTIFY_SOURCE, (see feature_test_macros(7) https://man7.org/linux/man-pages/man7/feature_test_macros.7.htm...
Answer
#1: Initial revision
strcpy(3) can be safe. Some compilers, such as GCC and Clang, use a feature test macro, `_FORTIFY_SOURCE`, (see feature_test_macros(7) <https://man7.org/linux/man-pages/man7/feature_test_macros.7.html>), to ask the compiler to add some checks to make sure that buffer overflow doesn't happen. If the bug is detected at compile time, it will raise a warning. If the bug is detected at run time, it will abort(3) the program. This is the simplest thing a programmer can do to prevent the problems that strcpy(3) can cause. --- ### Truncating Another way to avoid buffer overflow is truncating the string. This adds complexity to the code, which can itself cause more bugs. In general, if you can use `_FORTIFY_SOURCE`, it's preferred. If you do this, you need to: - Specify the limiting size. - Check the return value of the functions, to detect truncation. - Do something if you detect truncation! The last step is usually neglected, causing second-order bugs. Continuing the program with a truncated string can be very dangerous too. If you really need to do this, there's no standard function in ISO C. In POSIX, strlcpy(3) and strlcat(3) will be added soon (in Issue 8, POSIX.1-202x). If you need to chain several such calls, strlcat(3) is hard to use (you need to check the return value after every call); you may want to use stpecpy(3), which you'll need to write yourself (see `man 3 stpecpy` <https://man.archlinux.org/man/stpecpy.3> for a simple implementation). In case your system doesn't provide strlcpy(3), you may also want to write your own stpecpy(3) implementation.