title: abi::__cxa_demangle -- why buffer needs to be `malloc`-ed?
body: <p>The documentation of <code>abi::__cxa_demangle</code> (such as <a href="https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html" rel="nofollow noreferrer">https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html</a>) specifies that the second argument, <code>char * output_buffer</code>, need to be <code>malloc</code>-ed. </p>
  
  <p>That means that a character buffer allocated on the stack such as the following is not allowed.</p>
  
  <pre><code>  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, &amp;output_length, &amp;status);
  </code></pre>
  
  <p>Two questions:</p>
  
  <ol>
  <li><p>Why is an <code>output_buffer</code> on stack not allowed?</p></li>
  <li><p>Why is a different pointer returned when an output buffer was already passed?</p></li>
  </ol>
  
  <p>Influenced by the example of <a href="http://man7.org/linux/man-pages/man3/backtrace.3.html" rel="nofollow noreferrer">backtrace()</a>, I would have imagined an API like the following</p>
  
  <pre><code>// 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);
  </code></pre>