]> git.ipfire.org Git - thirdparty/systemd.git/commit
basic/stdio-util: introduce asprintf_safe
authorZbigniew Jędrzejewski-Szmek <zbyszek@amutable.com>
Tue, 3 Mar 2026 09:00:29 +0000 (10:00 +0100)
committerZbigniew Jędrzejewski-Szmek <zbyszek@amutable.com>
Fri, 6 Mar 2026 16:46:59 +0000 (17:46 +0100)
commit52abc9fe9655b21329eda7cf7a7d73fc3a7bdde7
tree482254e387d85de176f4f7e41fcaaad96e23773e
parentd1278e1847392ef5c46acd0f1da689d5c986b3d5
basic/stdio-util: introduce asprintf_safe

asprintf is nice to use, but the _documented_ error return convention is
unclear:
> If  memory  allocation  wasn't possible, or some other error occurs,
> these functions will return -1, and the contents of strp are undefined.

What exactly "undefined" means is up for debate: if it was really
undefined, the caller wouldn't be able to meaningfully clean up, because
they wouldn't know if strp is a valid pointer. So far we interpreted
"undefined" — in some parts of the code base — as "either NULL or a
valid pointer that needs to be freed", and — in other parts of the
codebase — as "always NULL". I checked glibc and musl, and they both
uncoditionally set the output pointer to NULL on failure.

There is also no information _why_ asprintf failed. It could be an
allocation error or format string error. But we just don't have this
information.

Let's add a wrapper that either returns a good string or a NULL pointer.
Since there's just one failure result, we don't need a separate return
value and an output argument and can simplify callers.
docs/CODING_STYLE.md
src/basic/meson.build
src/basic/stdio-util.c [new file with mode: 0644]
src/basic/stdio-util.h