【发布时间】:2017-07-10 22:17:00
【问题描述】:
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);
两个问题:
为什么不允许堆栈上的
output_buffer?为什么在已经传递了输出缓冲区时返回了不同的指针?
受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);
【问题讨论】:
-
如果需要对某些东西进行 malloc 处理,通常是因为其他东西会对其调用 free 或 realloc。
-
"为什么栈上的 output_buffer 是不允许的?" - "如果 output_buffer 不够长,使用 realloc 扩展。".
-
没错,来自您提供的链接。
If output_buffer is not long enough, it is expanded using realloc -
@DanielKamilKozar 答案部分如下。
-
谢谢大家。对不起,我没有仔细阅读并忽略了
realloc部分。