strcpy, strncpy - copy a string


  1. include <string.h>

char *strcpy(dest, const char *src);

char *strncpy(char *dest, const char *src, size_t n);


The strcpy() function copies the string pointed to by src (including the terminating `0' character) to the array pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

The strncpy() function is similar, except that not more than n bytes of src are copied. Thus, if there is no null byte among the first n bytes of src, the result wil not be null-terminated.

In the case where the length of src is less than that of n, the remainder of dest will be padded with nulls.


The strcpy() and strncpy() functions return a pointer to the destination string dest.


If the destination string of a strcpy() is not large enough (that is, if the programmer was stupid/lazy, and failed to check the size before copying) then anything might happen. Overflowing fixed length strings is a favourite cracker technique.


SVID 3, POSIX, BSD 4.3, ISO 9899


Rumour has it that the reason that strncpy() has such bizarre semantics (copying up to the entire length of the string and not leaving space for the terminating '0', and padding to the end of the buffer with '0's if it's shorter) come from the days when you could read/write a directory. If you wanted to create a hardlink you opened the directory for writing and wrote the filename and the inode number into the directory. The filename had to be exactly n bytes long and must be '0' padded (instead of just terminated), hence the strncpy() semantics. It's far too late now to change the semantics to something more sane, so the OpenBSD people are advocating the use of strlcpy(3)? instead. Note, in high performance applications, strlcpy(3)? is much faster than strncpy(3) as it doesn't waste time padding the entire string.


bcopy(3), memccpy(3), memcpy(3), memmove(3)

This page is a man page (or other imported legacy content). We are unable to automatically determine the license status of this page.