gpt4 book ai didi

c++ - abi::__cxa_demangle 不能重用自己返回的内存

转载 作者:搜寻专家 更新时间:2023-10-31 02:20:18 30 4
gpt4 key购买 nike

我尝试使用 abi::__cxa_demangle 来分解用户定义的类型:

#include <iostream>
#include <mutex>
#include <memory>
#include <string>
#include <typeinfo>

#include <cassert>
#include <cstdlib>

#include <cxxabi.h>

namespace
{

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wexit-time-destructors"
std::mutex m;
std::unique_ptr< char, decltype(std::free) & > demangled_name{nullptr, std::free};
#pragma clang diagnostic pop

}

inline
std::string
get_demangled_name(char const * const symbol) noexcept
{
if (!symbol) {
return "<null>";
}
std::lock_guard< std::mutex > lock(m);
int status = -4;
demangled_name.reset(abi::__cxa_demangle(symbol, demangled_name.release(), nullptr, &status));
return ((status == 0) ? demangled_name.get() : symbol);
}

template< typename ...types >
void
f(std::size_t const i)
{
using F = void (*)();
assert(i < sizeof...(types));
static F const a[sizeof...(types)] = {static_cast< F >([] () { std::cout << get_demangled_name(typeid(types).name()) << std::endl; })...};
return a[i]();
};

struct A {};
struct B {};
struct X {};
struct Y {};
struct Z {};

int
main()
{
for (std::size_t i = 0; i < 5; ++i) {
f< A, B, X, Y, Z >(i);
}
return EXIT_SUCCESS;
}

但是 abi::__cxa_demangle 返回 status "-3: One of the arguments is invalid."每隔一次。

在第一次调用时(对于 A)智能指针包含 nullptr 并且 abi::__cxa_demangle 返回零 status "0: The demangling operation succeeded." .但是文档说:

output_buffer: A region of memory, allocated with malloc, of *length bytes, into which the demangled name is stored. If output_buffer is not long enough, it is expanded using realloc. output_buffer may instead be NULL; in that case, the demangled name is placed in a region of memory allocated with malloc.

因此,我得出结论,该函数不能重复使用由其自身一致分配的内存。是错误还是我对文档的误解?

最佳答案

你误解了文档:

output_buffer: A region of memory, allocated with malloc, of *length bytes

您正在传递用 malloc 分配的内存区域,但 length 为空,因此 *length 未定义。

为了知道它是否可以重新使用内存,它需要知道 block 有多大,所以你需要传入长度作为第三个参数。

GCC 中的实现(实际上是在 libiberty support library 中):

  if (output_buffer != NULL && length == NULL)
{
if (status != NULL)
*status = -3;
return NULL;
}

因此,如果您传递一个非空的 output_buffer 指针,您还必须传递一个非空的 length 指针。

因为你不知道分配的 block 有多大,你可以用当前代码做的最好的事情是使用 strlen(demangled_name.get())+1 来找到最小长度肯定是分配了。

更好的方法是保留一个存储先前大小的 size_t 全局变量,并将其传入。您可能应该将它们全部包装在一个类中,而不仅仅是一堆全局变量。

关于c++ - abi::__cxa_demangle 不能重用自己返回的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32884628/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com