Overloading Global Operator New

Discussion in 'iOS Programming' started by Hollingsworth, Aug 10, 2011.

  1. Hollingsworth macrumors newbie

    Aug 10, 2011
    I'm having difficulties specifying the initialization order for some memory management tools.

    We start with an overload of the Global new operator:

    // standard new
    void * C_DECL operator new (size_t size) {
        return ALLOC(size);
    // standard delete
    void C_DECL operator delete (void * ptr) {
    // array new
    void * C_DECL operator new [] (size_t size) {
        return ALLOC(size);
    // array delete
    void C_DECL operator delete [] (void * ptr) {
    The macros pull / release memory from a pre-determined pool that is managed by the tool.

    According to developer.Apple.com, the global operator new will be used for all code even the system / platform code that gets compiled into the project. This is fine.

    The problem is in the initialization order. The macros ALLOC() and FREE() call functions that expect the memory tool to have been initialized prior to use. But the system code is calling global operator new prior to the initialization of the memory subsystem.

    For most GCC related platforms this can be fixed with the following code:

    MemorySubsystem  g_memoryPool __attribute__((init_priority(100))) ();
    Where 100 specifies the priority, the lower the number the sooner it gets initialized. 100 seems to be the base priority for user generated code. 99- throws up a compiler warning that "Requested init_priority is reserved for internal use."

    If we set the priority to 0, we get an Error, "Requested inti_priority is out of range.".

    We can ignore the warning for now, and set the Priority to 1. The highest priority allowed, which should make it the first thing initialized.

    MemorySubsystem  g_memoryPool __attribute__((init_priority(1))) ();
    Unfortunately, Thats not what happens.

    A different unit gets initialized first, which uses STL, STL in turn uses operator new, which calls into my code, and crashes becuase the MemorySubsystem has not been initialized.

    Here is the call stack:
    #6 is the initialization code for the unit.
    #1 calls my global operator new overload.
    #0 calls into my memory subsystem, where it crashes.

    Any help with specifying the proper initialization order would be greatly appreciated.


    Dan -

Share This Page