3 ms·
Excerpting from the article: > Now having a function like this in the standard library isn't such a bad thing in itself. It's designed to deal with a specializ
by geofft 10y ago
Excerpting from the article:
> Now having a function like this in the standard library isn't such a bad thing in itself. It's designed to deal with a specialized data structure ...
> The problem is that the name strncpy() strongly implies that it's a "safer" version of strcpy(). It isn't. ....
> It's because strncpy()'s name implies something that it isn't that it's such a trap for the unwary. It's not a useless function, but I see far more incorrect uses of it than correct uses. This article is my modest attempt to spread the word that strncpy() isn't what you probably think it is.
This argument seems correct to me. "Safer," here, does not mean "If you swap out every use of strcpy for a correct use of strncpy, you'll have fewer bugs." As the author is defining it, "safer" includes the risk that someone will be less rigorous with their code by assuming strncpy will solve all their problems. It won't. It will solve some of their problems, yes, but they still have to analyze their problem almost as rigorously as if they were using strcpy.
If a code reviewer cares deeply about strcpy and less deeply about strncpy (and anecdotally this is a thing code reviewers do), then in practice, the use of strncpy is not safer.
- dllthomas 10y agoActually, I think it's true that "If you swap out every use of strcpy for a correct use of strncpy, you'll have fewer bugs." Any use of strncpy that breaks would also have broken if strcpy had been used instead, and there exist some situations where strncpy would not break while strcpy would; for instance, if we just inspect a prefix of the resulting string. That said, it's certainly the case that most breaking uses of strcpy, if naively replaced with strncpy, still break.
- geofft 10y ago> Actually, I think it's true that "If you swap out every use of strcpy for a correct use of strncpy, you'll have fewer bugs." Yes, I agree that this statement is true. But my claim is that this is not what the article means by "safer", and the article's definition of "safer" is more useful. That is, people who are saying "The article is wrong because it is possible to use strncpy correctly in cases where strcpy was not being used correctly" are not disagreeing with the article so much as talking past it.
- dllthomas 10y agoFair enough.
- Jare 10y ago> they still have to analyze their problem almost as rigorously as if they were using strcpy. Why rigorously? A blind dest[n-1] = '\0'; always worked for me, the only assumption is that n > 0. (in larger projects and/or teams you won't stop there of course, but that's a different topic)