Friday, September 20, 2013

Why should you use strncpy instead of strcpy?

www.blogger.com/blogger.g?blogID=3857439785589817539#editor/target=post;postID=1092521179290748231

strncpy combats buffer overflow by requiring you to put a length in it. strcpy depends on a trailing \0, which may not always occur.
Secondly, why you chose to only copy 5 characters on 7 character string is beyond me, but it's producing expected behavior. It's only copying over the first n characters, where n is the third argument.
The n functions are all used as defensive coding against buffer overflows. Please use them in lieu of older functions, such as strcpy.
 
 
strncpy was initially introduced into the C library to deal with fixed-length name fields in structures such as directory entries
 
http://www.lysator.liu.se/c/rat/d11.html
 
memcpy
memmove
 
....
 
functions

chris & Sinan: It's getting upvotes because the question was, "Why would you use strncpy instead of strcpy?" Not, "What is strncpy for?" There's a distinct difference. This answer addresses the former, not the latter.
 
 
http://stackoverflow.com/questions/2593814/why-do-i-get-a-segmentation-fault-when-using-strncpy
 
The problem is that tp->mnem is pointing to a string literal, which is generally allocated in a read-only segment of memory. Therefore it's illegal to overwrite it. 

No comments:

Post a Comment