TL;DR
The strcpy function is dangerous because it doesn’t check the size of the buffer you’re copying into. This can lead to a buffer overflow, where data gets written past the end of the allocated memory. We’ll show how to fix this using safer alternatives like strncpy and by calculating buffer sizes before copying.
Understanding the Problem
A buffer overflow happens when you try to put more data into a space (the ‘buffer’) than it can hold. With strcpy, if the source string is longer than the destination buffer, it will write beyond the buffer’s boundaries, potentially overwriting other important data or even crashing your program.
How strcpy Causes Problems
Consider this example in C:
#include
#include
int main() {
char buffer[10];
char source[] = "This is a very long string";
strcpy(buffer, source);
printf("%sn", buffer);
return 0;
}
In this code, buffer can only hold 10 characters. However, source is much longer. When strcpy copies the string, it writes past the end of buffer, causing a buffer overflow.
Fixing the Overflow: Using strncpy
The strncpy function is a safer alternative to strcpy because you can specify the maximum number of characters to copy. However, it’s important to use it correctly:
- Specify the buffer size: Always provide the size of the destination buffer as the second argument to
strncpy. - Null-terminate manually:
strncpydoesn’t automatically add a null terminator if the source string is longer than or equal to the specified size. You need to do this yourself!
Here’s an example:
#include
#include
int main() {
char buffer[10];
char source[] = "This is a very long string";
strncpy(buffer, source, sizeof(buffer) - 1);
buffer[sizeof(buffer) - 1] = ' '; // Ensure null termination
printf("%sn", buffer);
return 0;
}
In this corrected code:
sizeof(buffer) - 1ensures we leave space for the null terminator.buffer[sizeof(buffer) - 1] = ' ';explicitly adds the null terminator, preventing potential issues.
Fixing the Overflow: Calculating Buffer Size
Another approach is to calculate the length of the source string and only copy if it fits within the destination buffer.
#include
#include
int main() {
char buffer[10];
char source[] = "This is a very long string";
size_t source_len = strlen(source);
if (source_len < sizeof(buffer)) {
strcpy(buffer, source);
} else {
printf("Source string too long to fit in buffer.n");
}
printf("%sn", buffer);
return 0;
}
This code checks the length of source before copying. If it's too long, it prints an error message instead of causing a buffer overflow.
Other Safer Alternatives
snprintf: This function is generally considered the safest option as it allows you to specify the maximum number of characters to write and always null-terminates the string.- Avoid
strcpyaltogether: In modern C++, consider usingstd::string, which automatically manages memory allocation and prevents buffer overflows.

