0

I wanted to set up a new embedded project using MicroC OS-II and use C++.

When I want to create an instance of a class using the new operator, my processor runs into an exception which seems to come from a failing malloc call in the new operator. This is an example that fails:

testC* test = new testC();

with testC being some class with an integer member variable. BTW, I am using Altera Nios 2.

After some research, I came to the conclusion that malloc is not compatible with the RTOS. Therefore my question: Is it possible to use C++ with uC/OS-II? Or is there a way to replace the malloc call in the new operator?

So far, I could not find any additional information about this.

Thank you very much for your help. Best, Roman

RMK
  • 3
  • 2
  • 1
    Out of curiosity, why are you using `new` in an embedded system? Most embedded systems have limited memory and no garbage collection. If you are going to use `new`, you'll have to resolve fragmentation issues. – Thomas Matthews May 19 '16 at 15:53
  • Well, I wanted to use C++ and make an OO system. And this is why I require the new operator, isn't it? I know that there is no gc, but this is C++ in general or I am wrong? – RMK May 20 '16 at 06:03
  • Does it make sense to use it that way or should I change my strategy? – RMK May 20 '16 at 06:40
  • In the embedded systems arena, a common paradigm is to prefer local variables (stack) and static variables (arrays, etc). The objective is to avoid fragmentation. – Thomas Matthews May 20 '16 at 15:23
  • A general *malloc()* implementation is not an absolute need to create an OO C++ application: You can (1) define yourself some memory pools (with items of the respective sizes your application needs) and allocator classes if you want - and use the placement-new operator instead of the vanilla one that goes to the system's malloc implementation (unless the latter doesn't exist...). Or, (2) you can design an OO application that doesn't use new/delete but creates all objects as members or stack variables - and live with the resulting constraints... – HelpingHand Feb 22 '22 at 21:31

1 Answers1

0

I found a solution to avoid the new operator while still maintaining the polymorphism (which is the actual reason for using a new operator). I create an object on the stack (or somewhere else), e.g. with

TestC test = TestC();

and in the actual code, I reference to the base class:

BaseC * base = &test;

Maybe this helps somebody else. Thanks everybody.

RMK
  • 3
  • 2
  • If you don't need the object to be mutable, it is even simpler: `BaseC const &base = TestC();`. – bipll May 20 '16 at 14:16