• R/O
  • SSH
  • HTTPS

molby: Commit


Commit MetaInfo

Revision624 (tree)
Time2019-08-17 17:52:26
Authortoshinagata1964

Log Message

Implementation of vsaprintf() is improved

Change Summary

Incremental Difference

--- trunk/MolLib/Missing.c (revision 623)
+++ trunk/MolLib/Missing.c (revision 624)
@@ -129,35 +129,28 @@
129129 #include <stdio.h>
130130 #include <errno.h>
131131
132+/* Portable implementation of vsaprintf by use of vsnprintf */
132133 int
133134 vasprintf(char **ret, const char *fmt, va_list ap)
134135 {
135- int size = 128;
136- char *buf;
137- buf = (char *)malloc(size);
136+ int size, n;
137+ char *buf;
138+ va_list argcopy;
139+ va_copy(argcopy, ap);
140+ size = vsnprintf(NULL, 0, fmt, argcopy); /* Returns the number of output characters */
141+ buf = (char *)malloc(size + 1);
138142 if (buf == NULL) {
139143 *ret = NULL;
140144 errno = ENOMEM;
141145 return -1;
142146 }
143- while (1) {
144- int n = vsnprintf(buf, size, fmt, ap);
145- if (n < 0)
146- break;
147- if (n >= size) {
148- size *= 2;
149- buf = (char *)realloc(buf, size);
150- if (buf == NULL)
151- break;
152- continue;
153- } else {
154- *ret = buf;
155- return n;
156- }
157- }
158- *ret = NULL;
159- errno = ENOMEM;
160- return -1;
147+ n = vsnprintf(buf, size + 1, fmt, ap);
148+ if (n < 0) {
149+ free(buf);
150+ return n;
151+ }
152+ *ret = buf;
153+ return n;
161154 }
162155
163156 int
Show on old repository browser