1STRCPY(3) Linux Programmer's Manual STRCPY(3)
2
3
4
6 strcpy, strncpy - copy a string
7
9 #include <string.h>
10
11 char *strcpy(char *dest, const char *src);
12
13 char *strncpy(char *dest, const char *src, size_t n);
14
16 The strcpy() function copies the string pointed to by src, including
17 the terminating null byte ('\0'), to the buffer pointed to by dest.
18 The strings may not overlap, and the destination string dest must be
19 large enough to receive the copy. Beware of buffer overruns! (See
20 BUGS.)
21
22 The strncpy() function is similar, except that at most n bytes of src
23 are copied. Warning: If there is no null byte among the first n bytes
24 of src, the string placed in dest will not be null-terminated.
25
26 If the length of src is less than n, strncpy() writes additional null
27 bytes to dest to ensure that a total of n bytes are written.
28
29 A simple implementation of strncpy() might be:
30
31 char *
32 strncpy(char *dest, const char *src, size_t n)
33 {
34 size_t i;
35
36 for (i = 0; i < n && src[i] != '\0'; i++)
37 dest[i] = src[i];
38 for ( ; i < n; i++)
39 dest[i] = '\0';
40
41 return dest;
42 }
43
45 The strcpy() and strncpy() functions return a pointer to the destina‐
46 tion string dest.
47
49 For an explanation of the terms used in this section, see
50 attributes(7).
51
52 ┌────────────────────┬───────────────┬─────────┐
53 │Interface │ Attribute │ Value │
54 ├────────────────────┼───────────────┼─────────┤
55 │strcpy(), strncpy() │ Thread safety │ MT-Safe │
56 └────────────────────┴───────────────┴─────────┘
58 POSIX.1-2001, POSIX.1-2008, C89, C99, SVr4, 4.3BSD.
59
61 Some programmers consider strncpy() to be inefficient and error prone.
62 If the programmer knows (i.e., includes code to test!) that the size
63 of dest is greater than the length of src, then strcpy() can be used.
64
65 One valid (and intended) use of strncpy() is to copy a C string to a
66 fixed-length buffer while ensuring both that the buffer is not over‐
67 flowed and that unused bytes in the destination buffer are zeroed out
68 (perhaps to prevent information leaks if the buffer is to be written to
69 media or transmitted to another process via an interprocess communica‐
70 tion technique).
71
72 If there is no terminating null byte in the first n bytes of src,
73 strncpy() produces an unterminated string in dest. If buf has length
74 buflen, you can force termination using something like the following:
75
76 if (buflen &