void * operator new( unsigned int iSize )
{
	static unsigned char aMemPool[10000];
	static unsigned iUsed = 0;
	iUsed += iSize;
	if( iUsed > 10000 )
	{
		return 0;
	}
	return &aMemPool[iUsed-iSize];
}

void MEM_UnitTest()
{
	for( int i = 0; i < 100000; i++ )
	{
		int *piTest = new int;
		*piTest = i;
		delete piTest;
	}
}

The function new returns a pointer to the end of the memory block, not the beginning. I think it would work if written like this:

void * operator new( unsigned int iSize )
{
    static unsigned char aMemPool[10000];
    static unsigned iUsed = 0;
                
    if( iSize == 0 || (iUsed+iSize) >= 10000 )
    {
        return 0;
    }
    // get pointer to betinning of the memory block
    unsigned char* ptr = &aMemPool[iUsed];
    // increment counter to beginning of next memory block
    iUsed += iSize;
    return ptr;
}

This code has at least two very serious flaws --
(1) because aMemPool is static and has scope only within the operator new, there is no way to release a memory block so that it can be used again. Any given block of memory can only be used once during the lifetime of the program.
(2) the delete operator on line 19 that you posted will not delete the memory allocated by the new operator and will cause the program to crash. In order for this to work correctly you need to write a delete operator and make the memory block public so that its visible to the delete operator. Also using a simple character array like that isn't going to work either because it isn't possible to mark memory blocks as either allocated or free. Allocating memory is a lot more complicated than the code you posted.

Two more things you can add to the list of things going wrong with it.

1. Your new function returns 0 when there is no more memory, it does not throw an exception. So it becomes your responsibility in the caller to check for NULL return before trying to use it.

2. Unless you take great care, you can't just take &aMemPool[iUsed-iSize]; and then use it as an int* without running into the possibility of alignment exceptions.

add this too. you have overloaded operator new, but not overloaded operator delete. so delete whatever will call the wrong operator delete; the results will not be pretty.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.