[ACCEPTED]-strncpy and using sizeof to copy maximum characters-strncpy

Accepted answer
Score: 15

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

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

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

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

Score: 7

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

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

You could allocate 1 a bigger buffer:

char buffer[bufferSize + 1];
strncpy( buffer, source, bufferSize );
*(buffer + bufferSize ) = 0;
Score: 4

Your idea:

call[strlen(call) - 1] = '\0';

would not work, as you would be 1 calling strlen() on a non-terminated string

Score: 1

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

No, strncpy does not promise 2 that target string would be null terminated.

char tar[2]={0,0};
char bar="AB";
strncpy(tar,bar,2);
// result tar[0]=='A'; tar[1]=='B'

It 1 order to make it correct you should use:

strncpy(traget,string,sizeof(target)-1);
target[sizeof(target)-1]=0
Score: 1

1) From cplusplus.com: "No null-character is implicitly 9 appended to the end of destination, so destination 8 will only be null-terminated if the length 7 of the C string in source is less than num." So 6 you if you need your string to be null-terminated, you 5 need to do this:

call[sizeof(call) - 1] = '\0';

A good way to do this would 4 be to write a wrapper function for strncpy that 3 always makes sure the string is terminated.

2) If 2 the source is shorter than the destination, the 1 destination will be null-terminated.

Score: 1

Just use strlcpy() instead of strncpy(). You'll 2 have to check if it's available on all platforms. Early 1 versions of linux probably don't have it.

Score: 1

Use strlcpy in same way as strncpy. no need 1 to do size-1 in 3rd parameter

i.e: strncpy(call, info.called, sizeof(call)-1); or strlcpy(call, info.called, sizeof(call));

More Related questions