I have a function that presumably leaks memory but I can't see where!

Hi,

The code below is reported by C++ Memory Validator to produce a leak, but I don't see how!


1
2
3
4
5
6
7
8
// convert wstring to string
inline std::string to_string(const std::wstring& str, const std::locale& loc = std::locale{})
{
	std::vector<char> buf(str.size());
	std::use_facet<std::ctype<wchar_t>>(loc).narrow(str.data(), str.data() + str.size(), '?', buf.data());

	return std::string(buf.data(), buf.size());
}


Regards,
Juan
Last edited on
seems like a false positive, unless there is an actual leak in other code and it's misattributing it here. Either way, I would send a bug report. Valgrind has no issues with this function.

(also, note that this is a pretty poor conversion, it kills every a non-ASCII value from your wide string. I would use std::codecvt_utf8 for something more reasonable)
Last edited on
Neither Valgrind nor Deleaker shown leaks in this code!
Thanks!!
I am very confused about using codecvt... Could Cubbi please show me how to accomplish the translation from wstring to string using the proposed codecvt_utf8?

Thanks,
Juan
sure:
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <codecvt>
#include <locale>
#include <string>
int main() {
    std::wstring ws = L"ハロー・ワールド";
    std::string s = std::wstring_convert<std::codecvt_utf8<wchar_t>>{}.to_bytes(ws);
    std::cout << s << '\n';
}

live demo https://wandbox.org/permlink/408oNI7UPGjQeD3x

(it may be convenient to create a converter once with std::wstring_convert<std::codecvt_utf8<wchar_t>> cvt; and use as-needed to call cvt.to_bytes(ws); or cvt.from_bytes(s);)
Last edited on
Topic archived. No new replies allowed.