I've read that malloc() should be avoided when designing FreeRTOS applications. Does the same apply when using "new"?
E.g.:
TestObject* test = new TestObject();
On a side note, can the FreeRTOS C files be compiled with a C++ compiler?
Electrical Engineering Stack Exchange is a question and answer site for electronics and electrical engineering professionals, students, and enthusiasts. It only takes a minute to sign up.
Sign up to join this communityI've read that malloc() should be avoided when designing FreeRTOS applications. Does the same apply when using "new"?
E.g.:
TestObject* test = new TestObject();
On a side note, can the FreeRTOS C files be compiled with a C++ compiler?
This isn't about malloc vs new, rather it is about "should you use heap allocation in an embedded system, or not?" which is more of a philosophical question.
Heap memory management is very useful from a programmer's point of view, however in an embedded / real time application, when an allocation fails, you're in trouble.
If all memory is preallocated (ie, statically), then you can prove that the software will never run out of memory. You can't prove it when using dynamic allocation. If you manage memory manually (which is a pain) there can also be memory leaks, double free's, and other fancy bugs. Additionally, since you are using a preemptive multitasking OS, you have to wonder if your memory allocator is thread-safe. If your code uses lots of allocations, overhead may be substantial.
Memory fragmentation is a real problem on long-running systems, too. And this one is quite subtle. You need an allocator designed to mitigate this, but it will only work if the allocations are small enough in size.
So... it's a tradeoff. You have to think about the details.
The issue is that dynamic memory support on embedded systems is often very limited. If you are working on a platform where it is advised to avoid malloc
, then you should also avoid new
as well.
There's no requirement in C++ to implement new
and delete
in any particular way, but generally the default implementations will use malloc
and free
under the hood.
There can be problems in compiling C files with a C++ compiler. For example, C++ has extra keywords such as "class" and "new" that could, in C, be used as variable or function names and would cause an error if compiled with a C++ compiler. The usual way around this is to surround the C code with constructs such as:
#ifdef __cplusplus
extern "C" {
#endif
// C source code
#ifdef __cplusplus
}
#endif
C++ compilers predefine __cplusplus to be non-zero, whereas C compilers do not define it.
If you check the FreeRTOS source and header files you will find that this has already been done, and so it should be safe to compile it with a C++ compiler.