Assertion while calling set_new_handler(). Why?

23 04 2008


C++ allows us to set a exception handling function, to handle memory allocation failures. When ever memory allocation failure occurs, this function will be called. See the following code block.

// Memory allocation error handler.
void __cdecl MyNewHandler()
{
    std::cout << "Allocation failed.";
}

void main()
{
    // Set the new handler
    set_new_handler( MyNewHandler );

    int *pi = new int[500000000];
}

Its valid, it calls the function to register the memory allocation failure handling function and it compiles. Perfect! But when you run it, it will show assertion. Do you know why?


You’ve missed an underscore. Yes, i really mean it! Actually the function you’ve to call for registering “new handler” is _set_new_handler(), not the set_new_handler(). The set_new_handler() is just a stub function, which is provided in the C runtime library to compile the STL. Its not indented to be used by us. See the correct usage of _set_new_handler() below.

#include <iostream>
#include <new.h>

// Memory allocation error handler.
int MyNewHandler( size_t size )
{
    std::cout << "Memory allocation failed!";
    return 0;
}

void main()
{
    // Set the new handler
    _set_new_handler( MyNewHandler );

    int *pi = new int[500000000];
}


This often happens when you use third party application such as Visual Assist for improved intellisense. The function it auto completes can be an existing one, but may waste several hrs of effort. isn’t it? 😉


Targeted Audience – Advanced.

Advertisements