Sign in to follow this  
Wavarian

Another question on global operator new.

Recommended Posts

Wavarian    850
Hey guys, Having fixed my previous problem (thanks again to those that helped), I decided to go ahead and experiment a little more with my custom new's implementation. For experimentation's sake, I made my version throw a custom exception object, instead of the standard std::bad_alloc object. Next, I simulated an out-of-memory scenario. The thing that happened next surprised me. My program crashed because std::string was using the new operator implementation, and attempted to write to a misallocated block of memory. After plugging about with the debugger, I say that what happened surprised me because string was calling my new operator within a try/catch block, and yet it still went ahead and tried to write to the invalid memory. Here's where the exception occurred: xmemory - line 34
		// TEMPLATE FUNCTION _Allocate
template<class _Ty> inline
	_Ty _FARQ *_Allocate(_SIZT _Count, _Ty _FARQ *)
	{	// allocate storage for _Count elements of type _Ty
	return ((_Ty _FARQ *)operator new(_Count * sizeof (_Ty)));
	}


And here's where the allocation function gets called: xstring - line 1453
		_TRY_BEGIN
			_Ptr = _Mybase::_Alval.allocate(_Newres + 1);
		_CATCH_ALL
			_Newres = _Newsize;	// allocation failed, undo roundup and retry
			_TRY_BEGIN
				_Ptr = _Mybase::_Alval.allocate(_Newres + 1);
			_CATCH_ALL
			_Tidy(true);	// failed again, discard storage and reraise
			_RERAISE;
			_CATCH_END
		_CATCH_END


So what's going on? Does this mean that if (heaven forbid) my application runs out of memory, string will crash? There's nothing wrong with the try/catch blocks, and yet my exception object doesn't get caught. Has anyone been curious enough to try this, or perhaps might even know about what's going on behind the scenes?

Share this post


Link to post
Share on other sites
Wavarian    850
Oh crap. I figured it out.. My exception object was trying to allocate the string internally. Bugger.

I like how std::bad_alloc uses character arrays for this exact reason =D

Regardless, I decided not to delete this post.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this