Export to GitHub

dynamic-cpp - issue #1

Potentially serious issue with the exception class.


Posted on Jun 28, 2014 by Grumpy Horse

The _message member variable of the exception class is a const char*. The constructor of the exception does the following.

_message = message;

The problem is that exceptions are thrown. This goes the exception to go beyond the context of the calling function.

This will work as long as the exception is used as follows.

throw exception("some quoted string.");

It works by chance because "some quoted string." is treated as a pointer to some fixed place in the final executable.

However, this will cause problems.

char message[1024]; /* code to format that message */ throw exception(message);

By the time what gets called, the _message member variable no longer points to valid data.

This is why std::exception copies the message, and does not just use =.

Here is the implementation from Visual Studio.

_EXCEPTION_INLINE __CLR_OR_THIS_CALL exception::exception( const char * const & _What) : _Mywhat(NULL), _Mydofree(false) { _Copy_str(_What); }

_Copy_str uses malloc and strcpy.

Here is the source of _Copy_str.

// _Copy_str() assumes that *this is already tidy. _EXCEPTION_INLINE void __CLR_OR_THIS_CALL exception::_Copy_str( const char * _What) { if (_What != NULL) { const size_t _Buf_size = strlen(_What) + 1; _Mywhat = static_cast<char *>(malloc(_Buf_size)); if (_Mywhat != NULL) { _CRT_SECURE_STRCPY(const_cast<char *>(_Mywhat), _Buf_size, _What); _Mydofree = true; } } }

Comment #1

Posted on Aug 7, 2014 by Grumpy Cat

This is more of a documentation issue. The intent of the dynamic::exception class was that it should always be called with a string literal for a message so that we could avoid a memory allocation.

Perhaps if the class was templated, we could detect if someone tried to call it with something other than a string literal and fail at compile time, but it doesn't seem to be worth the effort.

Status: WontFix

Labels:
Type-Defect Priority-Medium