diff options
author | Adam Borowski <kilobyte@angband.pl> | 2009-12-17 11:29:22 +0100 |
---|---|---|
committer | Adam Borowski <kilobyte@angband.pl> | 2009-12-17 11:29:22 +0100 |
commit | b7d134a9c8a634cdab2cd060e561304e1d12979d (patch) | |
tree | 6111047f1a143803d066df7ae8c775ed65109e8a /crawl-ref/source | |
parent | 51f76411e22a18ce0cb3fdf001bcb5e558532124 (diff) | |
download | crawl-ref-b7d134a9c8a634cdab2cd060e561304e1d12979d.tar.gz crawl-ref-b7d134a9c8a634cdab2cd060e561304e1d12979d.zip |
In make_sprintf(), don't call sprintf() twice if the first call succeeds.
This spares us the second call, a malloc() and free() in 99.999% cases.
Diffstat (limited to 'crawl-ref/source')
-rw-r--r-- | crawl-ref/source/libutil.cc | 15 |
1 files changed, 8 insertions, 7 deletions
diff --git a/crawl-ref/source/libutil.cc b/crawl-ref/source/libutil.cc index 9b8304a7ca..ace4a65309 100644 --- a/crawl-ref/source/libutil.cc +++ b/crawl-ref/source/libutil.cc @@ -140,15 +140,16 @@ std::string make_stringf(const char *s, ...) { va_list args; va_start(args, s); - - size_t len = vsnprintf(NULL, 0, s, args); - char *buf = (char *)malloc(len + 1); + char buf1[400]; + size_t len = vsnprintf(buf1, sizeof buf1, s, args); va_end(args); + if (len < sizeof buf1) + return (buf1); + char *buf2 = (char*)malloc(len + 1); va_start(args, s); - vsnprintf(buf, len + 1, s, args); - std::string ret(buf); - free(buf); - + vsnprintf(buf2, len + 1, s, args); + std::string ret(buf2); + free(buf2); va_end(args); return (ret); } |