3 ms·
> At first this looks great, but there is a problem. What happens when the source string minus the null terminator is as long as the size of the destination str
by kloch 4y ago
> At first this looks great, but there is a problem. What happens when the source string minus the null terminator is as long as the size of the destination string? The answer is that the destination gets filled with all the characters of the source string with no room left for the null terminator.
The 'n' in strncpy is mainly there to help you avoid overrunning the destination, it does not guarantee whatever makes in there is null-terminated.
This is why you should always explicitly set the last byte to zero after using strncpy (and never ever use strcpy).
char dest[16];
strncpy(dest, src, 15);
dest[15]=0;