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





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 that strncpy was 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


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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ