strncpy and using sizeof to copy maximum characters
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;
Your idea:
call[strlen(call) - 1] = '\0';
would not work, as you would be calling strlen()
on a non-terminated string