Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strncpy and using sizeof to copy maximum characters

Tags:

c

strncpy

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,

like image 246
ant2009 Avatar asked Jul 24 '09 09:07

ant2009


2 Answers

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

like image 156
Tim Sylvester Avatar answered Oct 31 '22 05:10

Tim Sylvester


If the source's length is less than the max number passed as third parameter strncpy will null-terminate the destination, otherwise - not.

If the source is equal or greater in length than the destination - it's your problem to deal with it. Doing like you suggest - calling strlen() - will not work since the buffer will be not null-terminated and you'll run into undefined behaviour.

You could allocate a bigger buffer:

char buffer[bufferSize + 1];
strncpy( buffer, source, bufferSize );
*(buffer + bufferSize ) = 0;
like image 23
sharptooth Avatar answered Oct 31 '22 04:10

sharptooth