the design of inner function _S_oom_malloc in SGI-STL allocator -
the code follows:
template <int __inst> void* __malloc_alloc_template<__inst>::_s_oom_malloc(size_t __n) { void (* __my_malloc_handler)(); void* __result; (;;) { __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 2 questions. 1. why _s_oom_malloc use infinite loop? 2. known, _s_oom_malloc called when malloc fails in __malloc_alloc_template::allocate function. , why use malloc allocate space?
anyone can me? lot.
first, loop not infinite. there 2 exits: throwing bad_alloc
exception allocating requested amount of memory. exception thrown when current new-handler null pointer.
to understand how can happen, consult e.g. item 49 effective c++. new-handler can either
- make more memory available
- install different new-handler
- deinstall new-handler (i.e. passing null pointer
set_new_handler
- throw exception
abort
orexit
second, reason uses c library's malloc
allocate space malloc
on systems well-tested , efficiently implemented function. standard library's new
functions "simply" exception-safe , type-safe wrappers around (which user can override, should want that).
Comments
Post a Comment