2 ms·
> The fact that I wasn't aware of a corner-case scenario where dst does not contain a string to begin with has in no way impeded my ability to type the above li
by byuu 13y ago
> The fact that I wasn't aware of a corner-case scenario where dst does not contain a string to begin with has in no way impeded my ability to type the above line correctly.
True. And again I was hesitant to say that, so I hope you didn't take any offense. These functions surprised me as well at first (I was personally bitten by that strlcpy() running full strlen(source) issue in my own XML parser.)
> I would be interested in a concrete example.
Well I don't really have a super-secure version. Honestly 99% of string stuff I do is using a C++ library that keeps track of the allocation size (and also has small-string optimization.)
What I came up with in place of strlcpy/cat, which worked better for my own purposes, is below, which I call strmcpy/cat:
//return = strlen(target)
unsigned strmcpy(char *target, const char *source, unsigned length) {
const char *origin = target;
if(length) { while(*source && --length) *target++ = *source++; *target = 0; }
return target - origin;
}
//return = strlen(target)
unsigned strmcat(char *target, const char *source, unsigned length) {
const char *origin = target;
while(*target && length) target++, length--;
return (target - origin) + strmcpy(target, source, length);
}
Truncation is detected by seeing if source[strmcpy/cat(...)] != 0, and very easy to wrap with another function. And in general, I find strcat functions kind of unpleasant (eg Schlemel the painter), so for that a strpcpy() that writes to a pointer will let you chain those, eg:
void strpcpy(char *&target, const char *source, unsigned &length) {
unsigned offset = strmcpy(target, source, length);
target += offset, length -= offset;
}
Now I am sure you can point out a myriad of serious problems with these functions, just as I have for strlcpy/cat.
Hell they're probably much worse than strl, but they work for me at least. If nothing else, they are at least easier to read =)
Full info on these functions is at the bottom of this dead article: http://web.archive.org/web/20130121234920/http://byuu.org/articles/programming/strcpycat http://web.archive.org/web/20130121234920/http://byuu.org/ar...