Difference between revisions of "c/string/byte/strncpy"
From cppreference.com
(Example showing: - →no buffer overflow: has buffer overflow. Fixed with: >> sizeof( copy )-1 <<) |
|||
Line 39: | Line 39: | ||
{ | { | ||
char str[] = "Hello, world!"; | char str[] = "Hello, world!"; | ||
− | char copy[40]; | + | char copy[40] = { 0 }; |
/* no buffer overflow */ | /* no buffer overflow */ |
Revision as of 03:56, 2 May 2014
Defined in header <string.h>
|
||
char *strncpy( char *dest, const char *src, size_t count ); |
(until C99) | |
char *strncpy( char *restrict dest, const char *restrict src, size_t count ); |
(since C99) | |
Copies at most count
characters of the byte string pointed to by src
(including the terminating null character) to character array pointed to by dest
.
If count
is reached before the entire string src
was copied, the resulting character array is not null-terminated.
If, after copying the terminating null character from src
, count
is not reached, additional null characters are written to dest
until the total of count
characters have been written.
If the strings overlap, the behavior is undefined.
Contents |
Parameters
dest | - | pointer to the character array to copy to |
src | - | pointer to the byte string to copy from |
count | - | maximum number of characters to copy |
Return value
dest
Example
Run this code
#include <stdio.h> #include <string.h> int main(void) { char str[] = "Hello, world!"; char copy[40] = { 0 }; /* no buffer overflow */ strncpy(copy, str, sizeof(copy)-1); printf("%s\n", copy); /* copy partial amount of data */ strncpy(copy, str, 5); /* add manually nullbyte. * comment it to see difference */ copy[5] = '\0'; printf("%s\n", copy); return 0; }
Output:
Hello, world! Hello
See also
(C11) |
copies one string to another (function) |
(C11) |
copies one buffer to another (function) |
C++ documentation for strncpy
|