Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I overload the new operator for multiple heaps?

In an embedded system with two separate RAM memory areas, I have two distinct heaps (one is a custom implementation from FreeRTOS in the lower memory area, another is the heap generated by GCC in the upper memory area) and I would like to be able to choose which heap new uses.

like image 788
Jacob Jennings Avatar asked Jul 26 '16 18:07

Jacob Jennings


People also ask

Is it possible to overload the new operators?

New and Delete operators can be overloaded globally or they can be overloaded for specific classes.

How many overloaded delete operator can be defined in a class?

In one class delete operator can be overloaded only once.

Why do we overload new and delete?

The most common reason to overload new and delete are simply to check for memory leaks, and memory usage stats. Note that "memory leak" is usually generalized to memory errors. You can check for things such as double deletes and buffer overruns.

Which operators Cannot be overloaded?

Detailed Solution. (::) Scope resolution operator cannot be overloaded in C language. Operator overloading:- It is polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform operations on user define data type.


1 Answers

You could provide an operator new overload that accepts a second argument telling it which memory area to allocate memory from. You can give arguments to operator new by putting them in parenthesis before the type in your new-expression. This is usually used to new an object into already-allocated storage (since that's the overload provided by the standard library), but anything can be passed there and it will be passed on to operator new.

enum MemoryArea {
    LOWER,
    UPPER
};

void* operator new(std::size_t sz, MemoryArea seg) {
    if (seg == LOWER) {
        return allocateMemoryInLowerMemoryArea(sz);
    } else {
        return allocateMemoryInUpperMemoryArea(sz);
    }
}

void operator delete(void* p) {
    if (pointerIsInLowerMemoryArea(p)) {
        freeMemoryFromLowerMemoryArea(p);
    } else {
        freeMemoryFromUpperMemoryArea(p);
    }
}

int main() {
    Foo* p = new (LOWER) Foo;
    Foo* b = new (UPPER) Foo;
    delete p;
    delete b;
}
like image 88
Miles Budnek Avatar answered Nov 15 '22 16:11

Miles Budnek