First, the loop is not truly infinite. There are two exits: by throwing a BAD_ALLOC
exception an by allocating the requested amount of memory. The exception will be thrown when the current new-handler is a null pointer.
To understand how that can happen, consult e.g. Item 49 from Effective C++. Essentially any new-handler can either
- Make more memory available
- Install a different new-handler
- Deinstall the new-handler (i.e. passing a null pointer to
set_new_handler
- Throw an exception
abort
orexit
Second, the reason that it uses the C library's malloc
to allocate space is that malloc
on most systems is a well-tested and efficiently implemented function. The Standard Library's new
functions are "simply" exception-safe and type-safe wrappers around it (which you as a user can also override, should you want that).