SysUtils.ShowException() allocates on (possibly corrupt) heap while promising not to do so

Summary

The documentation for 3.2.2 states the following :

The exception message can be at most 255 characters long: It is possible that no memory can be allocated on the heap, so ansistrings are not available, so a shortstring is used to display the message.

And there's also a corresponding comment near the function body:

// use shortstring. On exception, the heap may be corrupt.

However, the function code calls SysUtils.ExceptionErrorMessage(), which uses the heap explicitly:

  • it calls Format() which both takes and returns heap-based AnsiString values;

  • it stores the result of Format() in its own local AnsiString variable, from which it then copies to the output buffer.

System Information

  • Compiler versions: 3.2.2, trunk (f94f4e4e)

Possible fixes

Requires an implementation of Format() that either returns an explicit ShortString or outputs its result to a buffer provided by user. Unfortunately, FormatBuf() is unsuitable, as it is currently just a silly wrapper around Format() itself.

The ExceptionErrorMessage() function should be fixed too, because its requirement for heap makes it practically useless in the exception handling situations it is intended for.

Edited by Dmitry D. Chernov