From e6f72213b11241eaa1ffc1bca86baae26d6cb21b Mon Sep 17 00:00:00 2001 From: Erik Hofman Date: Sun, 3 Jul 2016 09:34:19 +0200 Subject: [PATCH] Detect the actual number of wchars required for the buffer and allocate it properly --- simgear/misc/sg_path.cxx | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/simgear/misc/sg_path.cxx b/simgear/misc/sg_path.cxx index bc0fc450..0d5140eb 100644 --- a/simgear/misc/sg_path.cxx +++ b/simgear/misc/sg_path.cxx @@ -987,17 +987,20 @@ std::string SGPath::join(const std::vector& paths, const std::string& jo std::wstring SGPath::wstr() const { #ifdef SG_WINDOWS - return std::wstring(); -#else - wchar_t wideBuf[2048]; - size_t count = mbstowcs(wideBuf, path.c_str(), 2048); - if (count == -1) { - return std::wstring(); - } else if (count == 2048) { - SG_LOG( SG_GENERAL, SG_ALERT, "SGPath::wstr: overflowed conversion buffer for " << *this ); - } - - return std::wstring(wideBuf, count); + size_t buflen = mbstowcs(NULL, path.c_str(), 0)+1; + wchar_t wideBuf = malloc(buflen * sizeof(int)); + if (wideBuf) { + size_t count = mbstowcs(wideBuf, path.c_str(), buflen); + if (count == -1) { + return std::wstring(); + } + + std::wstring rv(wideBuf, count); + free(wideBuf); + return rv; + } else { + SG_LOG( SG_GENERAL, SG_ALERT, "SGPath::wstr: unable to allocate enough memory for " << *this ); + } #endif } -- 2.39.5