• Welcome to Valhalla Legends Archive.
 

Overloading new

Started by Arta, February 18, 2004, 10:07 AM

Previous topic - Next topic

Arta

Is it possible to overload new at global scope and still call the original new from within that function?

Something like:


void *operator new(size_t Size)
{
   void *Ptr = ::operator new(Size);

   if(!Ptr)
   {
      // Memory allocation failed
      Output(MSG_FATAL, "Insufficient memory!\n");

      ExitProcess(0);
   }

   return Ptr;
}


...except that doesn't recurse.

Eibro

What are you trying to do? Provide extra handling if allocation fails? If so, see std::set_new_handler().
Eibro of Yeti Lovers.

Arta


Skywing

I'd use something else, like malloc or HeapAlloc.  No scoping tricks needed there.

You could also use the throwing new with exception handlers, as a possible alternative to set_new_handler if this fits your program better.

Arta

#4
is it safe to delete memory allocated with malloc? Pretty sure it is, but would like to confirm :)

Yoni

Quote from: Arta[vL] on February 19, 2004, 02:54 AM
is it safe to delete memory allocated with malloc? Pretty sure it is, but would like to confirm :)
No :)
Standard C++ says you can't mix them.

Maybe you can in specific compilers as an extension.

iago

I still remember a classic:

HashTable::~HashTable()
{
 delete table;
 free(position);
}

.. or something very similar to that.  It was about there that we scrapped it and started over :)
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


Skywing

#7
Quote from: Arta[vL] on February 19, 2004, 02:54 AM
is it safe to delete memory allocated with malloc? Pretty sure it is, but would like to confirm :)
No.  It's also not safe to delete memory allocated with new[].  Note that this is even true with VC - usually, if you mix the two, you'll cause heap corruption (at best) or crash immediately (at worst).

If you are overloading operator new, you should probably also overload operator delete.

Arta

#8
In which case, my original question stands. How do I avoid the scoping issue? Just curious now :)