openat: don’t close (-1)
[gnulib.git] / lib / vasprintf.c
blob757d1c740a8b8ed98bd6b432a0e5fee64b18fe91
1 /* Formatted output to strings.
2 Copyright (C) 1999, 2002, 2006-2024 Free Software Foundation, Inc.
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
9 This file is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 #include <config.h>
19 /* Specification. */
20 #ifdef IN_LIBASPRINTF
21 # include "vasprintf.h"
22 #else
23 # include <stdio.h>
24 #endif
26 #include <errno.h>
27 #include <limits.h>
28 #include <stdint.h>
29 #include <stdlib.h>
31 #include "vasnprintf.h"
33 int
34 vasprintf (char **resultp, const char *format, va_list args)
36 size_t length;
37 char *result = vasnprintf (NULL, &length, format, args);
38 if (result == NULL)
39 return -1;
41 #if PTRDIFF_MAX > INT_MAX
42 if (length > INT_MAX)
44 free (result);
45 errno = (length > PTRDIFF_MAX ? ENOMEM : EOVERFLOW);
46 return -1;
48 #else
49 if (length > PTRDIFF_MAX)
51 free (result);
52 errno = ENOMEM;
53 return -1;
55 #endif
57 *resultp = result;
58 /* Return the number of resulting bytes, excluding the trailing NUL. */
59 return length;