is my implementation of my strncpy right?
<String.h> is my implementation of my strncpy right?
char *strncpy(char *dest, char *src, unsigned int n)
unsigned int a;
a = 0;
while (src[a] && a < n)
dest[a] = src[a];
a++;
while (a < n)//if src not bigger than n should I put '' at the end of dest ?
dest[a] = '';
a++;
dest[a] = '';
return (dest);
Hello Stackoverflow
I am looking for my mistake, I know that when n > strlen(dest), it does abort on the real strncpy and I am wondering why it is wrong ?
Thanks for your help
strncpy
strncpy
@Louis Aspas - May you please rephrase your question. This code seems fine but am facing difficulty in understanding question that follows this code
– Rizwan
Aug 31 at 9:56
Your final
dest[a] = ''; is equivalent to dest[n] = ''; which writes beyond the assumed buffer size n .. The real strncpy() would only touch n` characters. [NOTE: the real strncpy() is almost useless]– joop
Aug 31 at 10:12
dest[a] = '';
dest[n] = '';
n
strncpy() would only touch
strncpy()
1 Answer
1
You no need to append '' continuously, if you want to rest of the memory of dest to be filled with zeros you can use calloc() while allocating memory
dest
calloc()
char *strnncpy(char *dest, char *src, unsigned int n)
unsigned int a;
a = 0;
while ( src[a] && a < n)
dest[a] = src[a];
a++;
dest[a] = '';
return (dest);
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
If you are making a function that works like
strncpy, you must also build in its flaws. See for example Why is strncpy insecure? and Why are strlcpy and strlcat considered insecure?. The key here is to realize thatstrncpywas added to the standard mostly by mistake, it was originally never intended to be used for null terminated C strings.– Lundin
Aug 31 at 9:43