Question

I'm using Keil 4 with ARM toolset for Cortex M3 (if that even matters). I tried this simple code:

class Base
{
    public:
    virtual ~Base() {}
};

class Derived : public Base
{

    public:
    int b;

    virtual ~Derived() {}
};

If I create an instance of Derived locally (inside main), everything is fine: debugging works, program size is about 300 bytes.

If I create an static or global instance of Derived, program size increases up to 1000 bytes and debug session stops on BKPT instruction.

I sorted out that's because heap size is set to its default value (zero). When I added some heap, debug started to work.

Making destructor protected, but non-virtual, resulted in the same behavior. Making usual method virtual did not.

So, my question is: For what reason does compiler need heap in this situation?

Vtab is created statically (I checked), global object should be static as well. It's sort of stupid to waste another 700 bytes for heap allocation code (and space for heap itself), when I don't need dynamic allocation.

(I made destructor virtual to prevent a warning.)

Was it helpful?

Solution 2

The answer is here, on Keil forum - http://www.keil.com/forum/21859/. The reason is generated function "__aeabi_atexit" which is called after return from main. Which is kinda funny, because this return will never happen in the embedded system.

OTHER TIPS

When the instance is defined outside of a function, two things happen. First, the constructor of the object is invoked before main is invoked. The programmer must be careful that the constructor does nothing that might require initialization that will occur later. Second, memory for the instance is allocated on the heap because there is no local scope prior to main. Embedded systems programmers must be especially careful about instantiating global objects. If the constructor relies on some hardware that is uninitialized before main, bad things can happen. Familiarize yourself with the C startup file provided by Keil (the assembly language module that calls main after initializing heap, copies flash to ram, and invokes global constructors).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top