strncpy and using sizeof to copy maximum characters

ant2009 picture ant2009 · Jul 24, 2009 · Viewed 16.4k times · Source

I am using the code below

char call[64] = {'\0'} /* clean buffer */
strncpy(call, info.called, sizeof(call));

I always use the sizeof for the destination for protecting a overflow, incase source is greater than the destination. This way I can prevent a buffer overflow as it will only copy as much as the destination can handle.

But I am now wondering if it will null terminate the destination.

A couple of cases.

1) If the source is greater. I could do this:

call[strlen(call) - 1] = '\0'; /* insert a null at the last element.*/

2) If the source is less than the destination. call is 64 bytes, and I copy 50 bytes as that is the size of the source. Will it automatically put the null in the 51 element?

Many thanks for any information,

Answer

Tim Sylvester picture Tim Sylvester · Jul 24, 2009

strncpy will not null-terminate the destination if it truncates the string. If you must use strncpy, you need to ensure that the result is terminated, something like:

strncpy(call, info.called, sizeof(call) - 1);
call[sizeof(call) - 1] = '\0';

BSD's strlcpy(), among others, is generally considered superior:

http://www.openbsd.org/cgi-bin/man.cgi?query=strlcpy