The documentation of abi::__cxa_demangle
(such as https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html) specifies that the second argument, char * output_buffer
, need to be malloc
-ed.
That means that a character buffer allocated on the stack such as the following is not allowed.
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);
Two questions:
Why is an
output_buffer
on stack not allowed?Why is a different pointer returned when an output buffer was already passed?
Influenced by the example of backtrace(), I would have imagined an API like the following
// 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);
If output_buffer is not long enough, it is expanded using realloc
– Wingerrealloc
part. – Sjambok