The code is as follows:
template <int __inst>
void*
__malloc_alloc_template<__inst>::_S_oom_malloc(size_t __n)
{
void (* __my_malloc_handler)();
void* __result;
for (;;) {
__my_malloc_handler = __malloc_alloc_oom_handler;
if (0 == __my_malloc_handler) { __THROW_BAD_ALLOC; }
(*__my_malloc_handler)();
__result = malloc(__n);
if (__result) return(__result);
}
}
I have two questions. 1. why does _S_oom_malloc use infinite loop? 2. as we known, _S_oom_malloc will be called when malloc fails in __malloc_alloc_template::allocate function. And why does it use malloc to allocate space?
Anyone can help me? Thanks a lot.
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
set_new_handler
abort
or exit
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).