strcpy() Copy an entire string
strcpy() Copy an entire string
strcpy() copies src and its null terminator to dest. Ensure strlen(src)+1 bytes fit; unterminated sources or overlapping regions cause undefined behavior.
| Category | string.h strings |
|---|---|
| Kind | Library function |
| Header | <string.h> |
| C standard | C89 / C90 |
📝 Syntax
char *strcpy(char *dest, const char *src);
⚙️ Parameters
| dest Required | A writable destination array with capacity of at least strlen(src) + 1. |
|---|---|
| src Required | The null-terminated source string to copy. |
Returns: Returns dest.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Hello, C!
⚠️ Warning strcpy() performs no bounds checking. dest must hold the source and its null terminator, and overlapping source and destination cause undefined behavior.
💡 Tip The example uses strlen(source) < sizeof destination to ensure there is room for the string including its null terminator.
🏷️ Related string.h functions
📚 Related Tutorials
❓ FAQ
QHow can I prevent destination overflow with strcpy?
ABefore copying, verify that strlen(src) + 1 fits in dest and that src is genuinely null-terminated. Do not copy directly when the source cannot be validated.
QCan the source and destination of strcpy overlap?
ANo. Overlap causes undefined behavior. Use a function such as memmove() when bytes must be moved between overlapping regions.
QWhich is safer, strcpy or strncpy, and how should I choose between them?
ANeither is automatically safe. strcpy requires a destination large enough for the source and its terminator; strncpy limits the write to n characters, but truncation may leave the destination unterminated, and shorter sources cause zero padding. Choose according to whether you need fixed-size records, always validate capacity and termination, and do not treat strncpy as a general-purpose safe copy function.