TL;DR
String functions are powerful but can cause problems if used carelessly (especially with user input). This guide shows how to use them safely, preventing crashes and security issues.
1. Understand the Risks
Common string function risks include:
- Buffer overflows: Writing past the end of a string’s allocated memory.
- Format string vulnerabilities: Using user input directly in format strings (e.g.,
printf). - Injection attacks: Malicious code embedded within strings that gets executed.
2. Choosing Safer Alternatives
Many languages offer safer string functions than older, potentially dangerous ones.
- C/C++: Avoid
strcpyandstrcat. Usestrncpyandstrncatinstead, *always* specifying the maximum buffer size. Even better, use standard library string classes likestd::stringwhich handle memory management automatically. - Python: Python strings are generally safer due to automatic memory management. However, be careful when using
evalorexecwith user-provided strings. - Java/C#: Use the built-in string classes and methods (e.g.,
String.copyValueOf(),StringBuilder). These handle memory safely.
3. Using `strncpy` Correctly (C/C++)
While better than strcpy, strncpy still requires care.
- Always specify the buffer size: This prevents writing past the end of your string.
char dest[20]; const char *src = "This is a long string"; sncpy(dest, src, sizeof(dest) - 1); // Leave space for null terminator - Null-terminate the destination:
strncpydoesn’t automatically add a null terminator if it copies fewer characters than the buffer size. You *must* do this manually.dest[sizeof(dest) - 1] = ' ';
4. Avoiding Format String Vulnerabilities
Never use user input directly in the format string of functions like printf or fprintf.
- Use placeholders: Pass user input as arguments to the function.
char *user_input = "Some text"; printf("User input: %s", user_input); // Correct // printf(user_input); // WRONG! Vulnerable to format string attacks
5. Input Validation and Sanitisation
Before using any user-provided string, validate and sanitise it.
- Check length: Ensure the string isn’t too long for your buffer.
- Filter characters: Remove or escape potentially dangerous characters (e.g., quotes, semicolons, special symbols).
- Use allowlists: Only permit specific characters that are known to be safe.
6. Example: Safe String Concatenation in C
Demonstrates a safer approach to string concatenation.
#include
#include
int main() {
char base[50] = "Initial text: ";
char addition[20] = "Added content";
size_t base_len = strlen(base);
size_t addition_len = strlen(addition);
if (base_len + addition_len < sizeof(base)) {
strcat(base, addition); // Safe because we checked the length
printf("%sn", base);
} else {
printf("String concatenation would overflow buffer.n");
}
return 0;
}
7. cyber security Considerations
Always treat user input as potentially malicious. Proper string handling is a crucial part of preventing injection attacks and other cyber security vulnerabilities.

