Originally Posted by
bithub
If you are dynamically allocating the memory to ensure the destination buffer has enough space to fit the string, there is no need to use strncpy(). In this case (as in your example), you can just use strcpy().
I want to echo this good advice, I feel like it's being lost in the thread.
Originally Posted by
slingerland3g
You are correct in using:
Code:
strncpy(dest, src, len + 1) ; // so it copies the null terminator too
Make sure you have room in the buffer. But why not just call strcpy()? (or, since you know the length, memcpy()?) If you just want to duplicate the string:
Code:
const char *src_string;
char *dst_string
Code:
// Quite possibly the easiest way...
// If your system doesn't have strdup(), write one.
dst_string = strdup(src_string);
or
Code:
dst_string = malloc(strlen(src_string) + 1);
if(!dst_string)
// No memory.
strcpy(dst_string, src_string);
or
Code:
size_t len = strlen(src_string);
dst_string = malloc(len + 1);
if(!dst_string)
// No memory.
// If strncpy() actually copies n chars, this will null terminate.
dst_string[len] = 0;
strncpy(dst_string, src_string, len);