3

abi::__cxa_demangle(例如https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html )的文档指定第二个参数 ,char * output_buffer需要malloc-ed。

这意味着不允许在堆栈上分配如下字符缓冲区。

  enum {N = 256};
  char output_buffer[N];
  size_t output_length = 0;
  int status = -4;
  char * const result = std::__cxa_demangle(mangled_name,
                        output_buffer, &output_length, &status);

两个问题:

  1. 为什么output_buffer不允许在堆栈上?

  2. 为什么在已经传递了输出缓冲区时返回了不同的指针?

backtrace()示例的影响,我会想象一个类似以下的 API

// Demangle the symbol in 'mangled_name' and store the output
// in 'output_buffer' where 'output_buffer' is a caller supplied
// buffer of length 'output_buffer_length'. The API returns the 
// number of bytes written to 'output_buffer' which is not
// greater than 'output_buffer_length'; if it is
// equal to 'output_buffer_length', then output may have been
// truncated.
size_t mydemangle(char const * const mangled_name,
                  char * output_buffer,
                  size_t const output_buffer_length);
4

2 回答 2

6

1) 为什么栈上的 output_buffer 是不允许的?

从您提供的链接。If output_buffer is not long enough, it is expanded using realloc. alloca由于堆栈帧通常具有固定大小(特殊情况),因此无法调整堆栈上的数据大小

2) 当一个输出缓冲区已经通过时,为什么会返回一个不同的指针?

当使用 realloc 时,没有理由认为你会得到相同的指针。例如,如果该位置没有足够的连续可用内存,则操作系统将需要在其他地方分配内存。

如果我不得不猜测为什么 API 是这样设计的,那通常认为不在函数中分配内存然后返回对该内存的引用是一种很好的做法。相反,让调用者负责分配和释放。这有助于避免意外的内存泄漏,并允许 API 用户设计自己的内存分配方案。我很欣赏这样的事情,因为它允许用户利用他们自己的内存管理方案来避免像内存碎片这样的事情。虽然这种潜在的使用realloc会使这个想法变得混乱,但是您可以通过为输出参数分配足够大的块来解决这个问题,这样realloc就永远不会调用它。

于 2017-07-10T22:24:11.697 回答
3
  1. 为什么不允许堆栈上的 output_buffer?
  2. 为什么在已经传递了输出缓冲区时返回了不同的指针?

因为 c++ 类名可以任意长。

试试这个:

#include <iostream>
#include <cxxabi.h>
#include <utility>

using foo = std::make_index_sequence<10000>;

int main()
{
    size_t buff_size = 128;
    auto buff = reinterpret_cast<char*>(std::malloc(buff_size));
    std::cout << "buffer before: " << static_cast<void*>(buff) << std::endl;
    int stat = 0;
    buff = abi::__cxa_demangle(typeid(foo).name(), buff, &buff_size, &stat);
    std::cout << "buffer after: " << static_cast<void*>(buff) << std::endl;
    std::cout << "class name: " << buff << std::endl;
    std::free(buff);
}

样本输出:

buffer before: 0x7f813d402850
buffer after: 0x7f813e000000
class name: std::__1::integer_sequence<unsigned long, 0ul, 1ul, 2ul, 3ul, 4ul, 5ul, 6ul, 7ul, 8ul, 9ul, 10ul, 11ul, 12ul, 13ul, 14ul, 15ul, 16ul, 17ul, ... and so on...
于 2017-07-10T23:05:39.373 回答