From: Kefu Chai Date: Wed, 9 Sep 2020 00:42:24 +0000 (+0800) Subject: common/BackTrace: let abi::__cxa_demangle() do the malloc X-Git-Tag: v16.1.0~1075^2 X-Git-Url: http://git-server-git.apps.pok.os.sepia.ceph.com/?a=commitdiff_plain;h=refs%2Fpull%2F37045%2Fhead;p=ceph.git 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 --- diff --git a/src/common/BackTrace.cc b/src/common/BackTrace.cc index 453ba02dbb9d..1dfa39cda176 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 + "()";