Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
MeasurementNew.cpp 1.39 KiB
/*
 * Author: Radovan Cerveny
 */

#include <cstdlib>
#include <new>
#include "MeasurementNew.hpp"
#include "measurements.hpp"

void * operator new( std::size_t n, bool measure ) {
	void * ptr = nullptr;

	for ( ; ; ) {
		 // allocate little more for extra info
		ptr = std::malloc ( n + sizeof ( std::size_t ) );

		if ( ptr != nullptr ) {
			 // store requested size before the block
			std::size_t * sptr = static_cast < std::size_t * > ( ptr );
			* sptr = n;
			sptr++;

			 // send it to the engine if it does not come from stealth allocation
			if ( measure )
				measurements::hint ( measurements::MemoryHint { measurements::MemoryHint::Type::NEW, n } );

			return static_cast < void * > ( sptr );
		}

		auto cur_handler = std::set_new_handler ( 0 );
		std::set_new_handler ( cur_handler );

		if ( cur_handler != nullptr )
			cur_handler ( );
		else
			throw std::bad_alloc ( );
	}
}

void * operator new( std::size_t n ) {
	return operator new( n, true );
}

void operator delete( void * ptr, bool measure ) noexcept {
	std::size_t * sptr = static_cast < std::size_t * > ( ptr );

	sptr--;

	 // read the block size and send it to the engine if it does not come from stealth allocation
	if ( measure )
		measurements::hint ( measurements::MemoryHint { measurements::MemoryHint::Type::DELETE, * sptr } );

	std::free ( sptr );
}

void operator delete( void * ptr ) noexcept {
	operator delete( ptr, false );
}