cstrncpy

strncpy and using sizeof to copy maximum characters


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,


Solution

  • 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;