The function strncpy()
doesn't always null terminate so I want to know what is the best alternative that always null terminates?
I want a function that if:
strlen(src) >= n /*n is the number of characters to be copied from source*/
there's no need to add further code like this:
buf[sizeof(buf)-1] = 0;
If the length of the string you desire to copy is unknown, you can use snprintf
here. This function sends formatted output to str. It acts similarily to sprintf()
, but instead does not write more bytes allocated by str. If the resulting string is longer than n-1
characters, then the remaining characters are left out. It also always includes the null terminator \0
, unless the buffer size is 0
.
This would be a alternative to strncpy()
or strcpy()
, if you really don't want to use it. However, manually adding a null terminator at the end of your string with strcpy()
is always a simple, efficient approach. It is very normal in C to add a null terminator at the end of any processed string.
Here is a basic example of using sprintf()
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 1024
int main(void) {
const size_t N = SIZE;
char str[N];
const char *example = "Hello World";
snprintf(str, sizeof(str), "%s", example);
printf("String = %s, Length = %zu\n", str, strlen(str));
return 0;
}
Which prints out:
String = Hello World, Length = 11
This example shows that snprintf()
copied over "Hello World"
into str
, and also added a \0
terminator at the end.
Note: strlen()
only works on null terminated strings, and will cause undefined behaviour if the string is not null terminated. snprintf()
also needs more error checking, which can be found on the man page.
As others have said, this is not an efficient approach, but it is there if you go looking.