From 141f23480e4851d4783877e14577c5792862dd6b Mon Sep 17 00:00:00 2001 From: Kefu Chai Date: Wed, 9 Sep 2020 08:42:24 +0800 Subject: [PATCH] common/BackTrace: let abi::__cxa_demangle() do the malloc also use the returned length for constructing the string_view to be appended. we could reuse the buffer across multiple demangle() call for saving the calls to malloc()/free(). but the upside of this change is that it's simpler. Signed-off-by: Kefu Chai --- src/common/BackTrace.cc | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/src/common/BackTrace.cc b/src/common/BackTrace.cc index 453ba02dbb9d7..1dfa39cda1762 100644 --- a/src/common/BackTrace.cc +++ b/src/common/BackTrace.cc @@ -51,23 +51,17 @@ std::string BackTrace::demangle(const char* name) int status; // only demangle a C++ mangled name if (mangled.compare(0, 2, "_Z") == 0) { - // just a guess, template names will go much wider - size_t len = 1024; - char* buf = (char*)malloc(len); - if (!buf) { - return {}; - } - if (char* demangled = abi::__cxa_demangle(mangled.c_str(), buf, &len, &status)) { + // let __cxa_demangle do the malloc + size_t len = 0; + if (char* demangled = abi::__cxa_demangle(mangled.c_str(), nullptr, &len, &status)) { std::string full_name{OPEN}; - full_name += demangled; + full_name += std::string_view(demangled, len); full_name += end; // buf could be reallocated, so free(demangled) instead free(demangled); return full_name; - } else { - // demangle failed, just pretend it's a C function with no args - free(buf); } + // demangle failed, just pretend it's a C function with no args } // C function return mangled + "()"; -- 2.39.5