SamTheMan
SamTheMan

Reputation: 405

c string copy with strncpy

I am really frustrated about strncpy function. I did something like this:

char *md5S; //which has been assign with values, its length is 44
char final[32];
strncpy(final,md5S,32);

but somehow the length of char final[] became more than 32 after.
What should I do here?

Upvotes: 5

Views: 18526

Answers (3)

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

strncpy does not NUL-terminate the copied string if the source string is as long as or longer than n characters. If you have access to it, you can use strlcpy, which will NUL terminate for you.

Do this instead:

strncpy(dst, src, dstlen - 1);
dst[dstlen - 1] = '\0';

OR

strlcpy(dst, src, dstlen);

where, for a char array, dstlen = sizeof(dst).

Upvotes: 6

Adam Hawes
Adam Hawes

Reputation: 5449

If your output buffer isn't large enough to copy all of the source string and its trailing NUL then the output string will not be NUL terminated.

In your case, the MD5 is 33 bytes including the NUL, so the NUL isn't copied. When you read the string back you're reading past the end of your buffer.

Make final 33 bytes long, and ALWAYS add a NUL to the last character in the destination when using strncpy.

int n = 32;
char *src = "some really really long, more than 32 chars, string."
char dst[n+1];

strncpy(dst, src, n);
dst[n] = '\0';

Upvotes: 2

rouzier
rouzier

Reputation: 1180

You forgot to leave room for the null character

char final[33];
strncpy(final,md5S,32);
final[32] = '\0';

Upvotes: 12

Related Questions