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,
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With