Recently I ran the following code on ideone.com (gcc-4.3.4)
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <new>
using namespace std;
void* operator new( size_t size ) throw(std::bad_alloc)
{
void* ptr = malloc( 2 * 1024 * 1024 * 1024);
printf( "%p\n", ptr );
return ptr;
}
void operator delete( void* ptr )
{
free( ptr );
}
int main()
{
char* ptr = new char;
if( ptr == 0 ) {
printf( "unreachable\n" );
}
delete ptr;
}
and got this output:
(nil)
unreachable
although new
should never return a null pointer and so the caller can count on that and the compiler could have eliminated the ptr == 0
check and treat dependent code as unreachable.
Why would the compiler not eliminate that code? Is it just a missed optimization or is there some other reason for that?