Skip to content

Commit

Permalink
Use vector instead of realloc for vprintf
Browse files Browse the repository at this point in the history
  • Loading branch information
ioan-chera committed Sep 2, 2023
1 parent aef3b7d commit 34b5e55
Showing 1 changed file with 4 additions and 7 deletions.
11 changes: 4 additions & 7 deletions src/m_strings.cc
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ SString SString::vprintf(const char *format, va_list ap)
// Algorithm: keep doubling the allocated buffer size
// until the output fits. Based on code by Darren Salt.

char *buf = NULL;
std::vector<char> buf;
int buf_size = 128;

for (;;)
Expand All @@ -217,19 +217,16 @@ SString SString::vprintf(const char *format, va_list ap)

buf_size *= 2;

buf = (char*)realloc(buf, buf_size);
if (!buf)
ThrowException("Out of memory (formatting string)\n");
buf.resize(buf_size);

out_len = vsnprintf(buf, buf_size, format, ap);
out_len = vsnprintf(buf.data(), buf_size, format, ap);

// old versions of vsnprintf() simply return -1 when
// the output doesn't fit.
if (out_len < 0 || out_len >= buf_size)
continue;

SString result(buf);
free(buf);
SString result(buf.data());
return result;
}
}
Expand Down

0 comments on commit 34b5e55

Please sign in to comment.