5

Can I do something like this:

#ifdef FREERTOS

#define malloc(size) pvPortMalloc(size)
#define free(ptr) pvPortFree(ptr)

#endif

and expect it to always call pvPortMalloc() instead of malloc()?

Also, what difference would it make putting this before/after #include <stdlib.h>?

I have some code that I would like to run both in and out of FreeRTOS, I would like to replace all the calls to malloc() with calls to pvPortMalloc() when using FreeRTOS.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jayjay
  • 1,017
  • 1
  • 11
  • 23
  • possible duplicate of [Create a wrapper function for malloc and free in C](http://stackoverflow.com/questions/262439/create-a-wrapper-function-for-malloc-and-free-in-c) – Elias Van Ootegem Jun 10 '14 at 12:52
  • `pvPortMalloc` is routine of allocating memory of FreeRTOS which is deffer for different algorithem of heap allocation.FreeRTOS internallaly used it for allocation memory for task,queue etc. You can do wrapper `malloc` as you done by `#ifdef FREERTOS...#endif`. It's replace all `malloc` to `pvPortMalloc` if `FREERTOS` defined. – Jayesh Bhoi Jun 10 '14 at 12:55

2 Answers2

2

You can use custome malloc as per your requirement. And already you have done also.

#ifdef FREERTOS

#define malloc(size) pvPortMalloc(size)
#define free(ptr) pvPortFree(ptr)

#endif

So when you want to use code with FreeRTOS then define FREERTOS flag. So it will use pvPortMalloc for memory allocation defined by freeRTOS from different heap management schemes (heap_1.c,heap_2.c,heap_3.c or heap_4.c) .

Without FreeRTOS not require to define.So it will use inbuilt malloc from #include <stdlib.h>

Also, what difference would it make putting this before/after "#include"?

I say no difference in it.

Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
  • The C library internally will generally be linked to malloc, so this #define will not work. Especially on newlib, you need to have a strongly linked symbol for __malloc_r, which things like printf will use internally to allocate an internally used buffer. http://www.nadler.com/embedded/newlibAndFreeRTOS.html has some details. – rounin Dec 30 '18 at 02:02
1

This will not work properly:

#define malloc(size) pvPortMalloc(size)
#define free(ptr) pvPortFree(ptr)

If you use printf, sprintf or some other functions from the standard library, it will call malloc_r, which isn't save for threads!

And yet, I have no idea how to redefine malloc and free

shauryachats
  • 9,975
  • 4
  • 35
  • 48
maslovw
  • 99
  • 6
  • 1
    See http://www.nadler.com/embedded/newlibAndFreeRTOS.html for some hints. Generally you need to implement __malloc_lock and __malloc_unlock, and __malloc_r and friends. – rounin Dec 30 '18 at 02:00