C Tips
Enable Javascript to display Table of Contents.
strncpy()
The typical error would look like this:
#include <string.h>
#include <stdio.h>
int main()
{
const char *src = "123456789";
char dst[5];
strncpy(dst, src, sizeof(dst));
for (int cnt=0; cnt < sizeof(dst); cnt++)
{
printf("%2d. 0x%x '%c'\n", cnt, dst[cnt], dst[cnt]);
}
}
We see that the terminating '\0'
is missing:
$ ./main
0. 0x31 '1'
1. 0x32 '2'
2. 0x33 '3'
3. 0x34 '4'
4. 0x35 '5'
$
If we cannot be sure that the source string is less or equal in length to the
destination, we have to write the following construct:
strncpy(dst, src, sizeof(dst)-1);
dst[sizeof(dst)-1] = '\0';