mirror of
https://github.com/systemd/systemd.git
synced 2026-07-01 20:27:09 +00:00
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.
19 lines
395 B
C
19 lines
395 B
C
/* SPDX-License-Identifier: LGPL-2.1-or-later */
|
|
|
|
#include "alloc-util.h"
|
|
#include "stdio-util.h"
|
|
|
|
char* asprintf_safe(const char *restrict fmt, ...) {
|
|
_cleanup_free_ char *buf = NULL;
|
|
va_list ap;
|
|
int r;
|
|
|
|
va_start(ap, fmt);
|
|
r = vasprintf(&buf, fmt, ap);
|
|
va_end(ap);
|
|
|
|
if (r < 0)
|
|
return NULL;
|
|
return TAKE_PTR(buf);
|
|
}
|