Comment by TazeTSchnitzel
2 years ago
If you ever find yourself writing strcpy() followed by strcat(), consider:
snprintf(buf, sizeof(buf), "%s%s", a, b);
This as safe as strlcpy and strlcat, but more efficient, and has been standard for 24 years.
1. This returns an int.
2. This is inefficient in a similar way that strlcpy is: it does more work than the size of the buffer.
1. This is only slightly less irrelevant than "this returns a size_t" if that were so.
2. You have the option to provide the length, snprintf(buf, sizeof buf, "%.*s%.*s", len1, str1, len2, str2);
If you're bottlenecked by snprintf (hint: you aren't) then snprintf isn't your API anyway. Write some more custom code, probably some memcpy's etc.
For 1: returning an int means that you get some unspecified behavior on overflow. For 2 then you need to call strlen yourself which kind of defeats the point of using snprintf because you can just use memcpy instead.
2 replies →
Honestly just use memcopy and define your own string structure.
C has void*, that allows you to implement easily modifiable data structures. There is a bit of 'NIH' syndrome in what I'm saying, I'll admit, but in the end it's better imho.
C is all about memory management and copying data around, and people can't stop whining that there is no magic string handling sauce (as if strings were special), and keep acting like we had to put up with the ridiculous strcat() etc. nonsense.
That's not what 'void*' is for.
That's how I use it though. As a data-agnostic type, so I can put whatever I like in my btrees/buffers/linked lists.
I don't use it for string management, I guess reading my post again, I expressed myself poorly, again.
Be careful, this does not work if buf is 'char*' rather than an array type.
asprintf is even better (although different because it allocates a new string).