Preventing Buffer Overflow in C strcpy Function
When using the strcpy function, if the source string is too long, it may cause a buffer overflow in the target string, leading to program crashes or data corruption. To prevent this situation, we can check the length of the source string before calling the strcpy function, and then choose an appropriate course of action, such as copying only a portion of the content or using a safer function instead of strcpy.
Here is a simple example code demonstrating how to handle cases where the source string is too long:
#include <stdio.h>
#include <string.h>
void safe_strcpy(char *dest, const char *src, size_t dest_len) {
if(strlen(src) < dest_len) {
strcpy(dest, src);
} else {
strncpy(dest, src, dest_len - 1);
dest[dest_len - 1] = '\0';
}
}
int main() {
char dest[10];
const char *src = "This is a very long string";
safe_strcpy(dest, src, sizeof(dest));
printf("Copied string: %s\n", dest);
return 0;
}
In the above example, we have defined a safe_strcpy function to replace the strcpy function, which takes the size of the destination string buffer as a parameter. Inside the function, we first check if the length of the source string is less than the size of the destination string. If it is, we directly use the strcpy function for copying. If not, we use the strncpy function to copy only a portion of the content, and manually add the null character ‘\0’ at the end to ensure the integrity of the string.
Through this method, we can effectively prevent buffer overflow problems caused by the source string being too long, ensuring the stability and security of the program.