Alejandro Colomar <[email protected]> writes: >> I'm confused, isn't this the same functionality as asprintf which >> POSIX.1-2024 added? > > Yes. > >> If so, why add it under a new name? > > asprintf(3) is a bad design. Here's the relevant text of the proposal: > > [...]. GNU and the > BSDs have it as asprintf(3), but there seems to be consensus > that this API isn't very well designed; evidence of this is that > the behavior is slightly different in the various > implementations, and has changed through history. > > Another design is closer to strdup(3). Plan9 has smprint(2), > which behaves basically like strdup(3), except for formatting > the string. This API matches the internal APIs implemented in > projects like the Linux kernel (kvasprintf()) and shadow-utils > (aprintf()). This one has the advantage that the attributes > such as [[gnu::malloc(free)]] can be applied to it. > > It is common to use such APIs together with code that calls > strdup(3). Here's an example from shadow utils: > > src/userdel.c-1062- if (prefix[0]) { > src/userdel.c:1063: user_home = xaprintf("%s/%s", > prefix, pwd->pw_dir); > src/userdel.c-1064- } else { > src/userdel.c-1065- user_home = > xstrdup(pwd->pw_dir); > src/userdel.c-1066- } > > This kind of code tends to favour the Plan9 API variant in > comparison with the GNU variant which doesn't fit well in > surrounding code.
I strongly disagree. The asprintf function allows you to get the length of the resulting string without calling strlen afterwards. This version will have to keep track of that information internally anyways or else it will not know where to write the next character. If someone wants it to return a pointer they can easily write an inline function for it. Collin
