0
votes

Suppose I have an array of size 10 characters (memset to 0), which I am passing to strncat as destination, and in source I am passing a string which is say 20 characters in length (null terminated), now should I pass the 'count' as 10 or 9?

The doubt is, does strncpy considers the 'count' as size of destination buffer or does it just copy 10 characters to the destination and then append a NULL terminating character in the 11th position.

Sorry if the question appears too trivial, but I was unable to make this out from the help documentation of strncpy.

5

5 Answers

3
votes

You should probably just read the man page a bit more. The operative sentence seems to be this one:

The strncat() function is similar, except that it will use at most n characters from src. Since the result is always terminated with '\0', at most n+1 characters are written.

2
votes

strncat will apply the null terminal for you. Since it has no knowledge about the alleged string you are pointing to, it will assume there is space for the null terminal. So you want to pass in 9.

2
votes

If your array only has room for 10 characters then your count should be 9, as strncat will try to append count characters from src plus a null terminator.

Also, in this case your destination should have a null terminator in the first position, because that is where you need it to start appending.

1
votes

$ man strncat

If src contains n or more characters, strncat() writes  n+1  characters
to  dest  (n  from src plus the terminating null byte).  Therefore, the
size of dest must be at least strlen(dest)+n+1
1
votes

The simple answer is: Ensure your buffer is big enough, if your buffer is to hold 10 characters, add one on to the size of the buffer to accomodate the nul character \0. That cannot be stressed enough and is one of the biggest stumbling blocks of learning C.

If you did not specify the appropriate length excluding the nul character, the buffer overflows and unpredictable results will occur, such as program crash, or jump off into the woods never to be seen again.

Hope this helps, Best regards, Tom.