TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Stop using strncpy already

37 pointsby UberMouseabout 12 years ago

15 comments

unwindabout 12 years ago
It's good to see some publicity around this, my experience from Stack Overflow tells me few C programmers know about these details.<p>That said, if the article's code would have appeared on Stack Overflow, I wouldn't be able to prevent myself from also saying:<p>The author's suggested replacement, the C++ template function (!) strcpy_safe(), is not so hot in my opinion.<p>It uses strncpy(), which is record-oriented and thus will <i>always</i> fill all its n bytes. If you do:<p><pre><code> char bigbuf[1024]; strncpy(bigbuf, "foo", sizeof bigbuf); </code></pre> Then strncpy() will happily 0-fill <i>all</i> of that buffer space, which of course is completely pointless and just a waste of precious cycles. This is because it treats the buffer as a "record", and insists to initialize all of it.<p>This is the "flip side" of the logic that prevents it from 0-terminating if the string fills the buffer; since the buffer is a record with a known size, and not really a C string, it doesn't need to be terminated, right? Heh.<p>Also, POSIX reserves the namespace of functions whose names start with "str". I'm not 100% sure how well this applies to C++, but it seems prudent to avoid defining your own function with a name like that.
评论 #5491666 未加载
cpresseyabout 12 years ago
"Stop using strncpy already!"... or you might as well write an article called "Stop using null-terminated strings already!"... or since many commenters here have already pointed that out, and the author is talking about C++ anyway, perhaps "Stop fearing std::string already!"
charliesomeabout 12 years ago
Here's a better idea: Stop using the str* functions completely. Start using buffers with explicit length fields attached, and start using the mem* functions.
评论 #5491639 未加载
shin_laoabout 12 years ago
On Windows you should use the secure C API functions such as strcpy_s.<p>In C++ using these function is just plain nonsense. Use std::string or equivalent.
InclinedPlaneabout 12 years ago
Null terminated strings are one of the worst failures of design in programming languages of all time. In C you're sort of stuck with turd polishing. It's never going to be good or right, it's always going to be partly broken in some way.<p>If I were writing a new code-base in C I'd standardize on using bstring but that too doesn't solve every problem.
评论 #5492073 未加载
IgorPartolaabout 12 years ago
So this safe function cannot be used with dynamically allocated buffers without casting them? That means it takes away the benefit of not passing in the size explicitly. It also does not deal with wide chars.<p>I think storing sizes explicitly is the better solution. If what you are dealing with are actually character strings, then you might store the byte size along with the char count.<p>If you are only dealing with ASCII (are you sure?), you could use memcpy and avoid the strncpy zero fill behavior.
primiturabout 12 years ago
From the article:<p>&#62;In order to use these functions correctly you have to do this sort of nonsense.<p><pre><code> char buffer[5]; strncpy(buffer, “Thisisalongstring”, sizeof(buffer)); buffer[sizeof(buffer)-1] = 0; </code></pre> Actually, its more like this:<p><pre><code> char buffer[5] = {0}; strncpy(buffer, "This is a long string", sizeof buffer - sizeof buffer[0]); </code></pre> (edit: sizeof, not sizeof()! edit2: bugfix!)<p>But okay, maybe your compiler won't let you do that (it should). Oh. We've already touched on what <i>Microsoft</i> won't let you do .. maybe Microsoft won't let you do that. (In which case the answer should be: don't use Microsoft).<p>But anyway .. then the author says this:<p>&#62;We are programmers, are we not? If the functions we are given to deal with strings are difficult to use correctly then we should write new ones.<p>Umm: NO! Learn to use your tools properly and stop re-inventing the wheel to fit your misunderstanding of the world! <i>BILLIONS</i> of lines of code out there use strncpy() and other n-fn variants, and guess what: even in safety-critical, life-threatening, embedded environments!<p>This article should really be titled: "If you are going to use strncpy(), and you're scared of it, THEN DON'T DEPLOY WITHOUT FULL CODE COVERAGE TESTING!"<p>NB: edit2 GOTCHA! Coverage, people.
评论 #5491569 未加载
评论 #5491444 未加载
评论 #5491435 未加载
bjourneabout 12 years ago
This is an excellent post to show everyone who says that C is easy. Or that only sucky programmers creates segfaults and all you need is some discipline. Not even very experienced developers can be expected to keep track of all the nuances of the various ??str??cpy functions and their various faults. The solution is to <i>stop using C already</i> (unless you really, really have to).
评论 #5491701 未加载
评论 #5491970 未加载
zokierabout 12 years ago
Seems bit odd to recommend his own function when the only complaint about strlcpy is that "it isn’t natively available in VC++.". I don't see how rolling your own is an improvement over battle-tested external function.
nateguchiabout 12 years ago
Oh the joys of c...
评论 #5510013 未加载
jstanleyabout 12 years ago
Am I missing something obvious? I don't profess to know C++, but surely the proposed solution only works when writing to an array? There is no way for the compiler to know how much space has been allocated for arbitrary pointers.
评论 #5491951 未加载
hp50gabout 12 years ago
There's nothing wrong with strncpy if you know what you are doing. The problem is that far too few people know what they are doing and don't how to check if what they're doing is correct or not.
chrisdewabout 12 years ago
asprintf already relieves this headache...<p><a href="http://linux.die.net/man/3/asprintf" rel="nofollow">http://linux.die.net/man/3/asprintf</a>
评论 #5491878 未加载
bradheabout 12 years ago
Yeesh, everyone is so angry in this thread...
evilrevolutionabout 12 years ago
No!