strcpy in C: How String Copying Works & Preventing Overflows
strcpy in c copies null terminated strings which means it copies all the bytes from the source string including the terminating '\0' to a destination character array. In c, strcpy is fast when the caller has already checked that the destination buffer is definitely larger than strlen(src) + 1; strcpy in c without prior length check is a major source of stack buffer overflows. For modern C17 code, use bounded string functions other than strcpy after checking the length, and avoid passing overlapping arguments, because any kind of overlapping copies is undefined behavior.
strcpy in C: String Copying, Buffer Capacity & Safe Alternatives — Technical Overview
strcpy in c copies null terminated strings which means it copies all the bytes from the source string including the terminating '\0' to a destination character array. In c, strcpy is fast when the caller has already checked that the destination buffer is definitely larger than strlen(src) + 1; strcpy in c without prior length check is a major source of stack buffer overflows. For modern C17 code, use bounded string functions other than strcpy after checking the length, and avoid passing overlapping arguments, because any kind of overlapping copies is undefined behavior.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *src = "Safe Copy";
char dst[32];
if (strlen(src) + 1 <= sizeof(dst)) {
strcpy(dst, src);
printf("Copied string: %s\n", dst);
}
return 0;
}
Runnable C example
#include <stdio.h>
#include <string.h>
int main(void) {
const char *src = "Safe Copy";
char dst[32];
if (strlen(src) + 1 <= sizeof(dst)) {
strcpy(dst, src);
printf("Copied string: %s\n", dst);
}
return 0;
}Expected Output
Copied string: Safe Copy