Designing a Better strcpy (2020)
19 hours ago
- #C Programming
- #String Manipulation
- #Security
- strxcpy is a proposed string copying function in C designed to copy a null-terminated source string to a destination buffer with bounds checking.
- It ensures the destination buffer contains a null-terminated prefix of the source string when possible, avoiding unterminated strings.
- The function returns the number of characters copied and indicates if an overflow occurred, allowing for handling truncation if needed.
- It aims for efficiency by running in a single pass, not reading or writing unnecessary memory, and being vectorizable for performance.
- Standardization (e.g., in ISO C or POSIX) is desired for portability, but strxcpy currently lacks this.
- Common existing functions like strcpy, strncpy, memcpy, and others have limitations: strcpy lacks bounds checks, strncpy doesn't null-terminate in all cases, memcpy ignores null characters, and strlcpy is non-standard and slower.
- strscpy meets functional requirements but is non-standard (Linux kernel-specific), while memccpy (an upcoming C standard/POSIX extension) can be adapted to achieve strxcpy's goals effectively.
- The article highlights the challenges in C string copying, advocating for safer and more efficient alternatives like memccpy to replace flawed existing functions.