# \[REENTRANT\] malloc function in libc sprintf type functions

**URL:** <https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020>\
**Category:** Kernel\
**Created:** [January 24, 2024, 12:10pm UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020 "2024-01-24T12:10:05Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yao](https://avatars.discourse-cdn.com/v4/letter/y/2bfe46/32.png) [@Yao](https://forums.freertos.org/u/Yao)\
**Post date:** [January 24, 2024, 12:10pm UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/1 "2024-01-24T12:10:05Z")

</div>

HI all,

About newlib reent question, I have check [LINK](https://nadler.com/embedded/newlibAndFreeRTOS.html), which should enable `configUSE_NEWLIB_REENTRANT`option in freertos config file for thread safe function.  
I have the following 2questions:

1. Is is ok to use pvPortMalloc() to wrap the malloc defined in libc for thead safe without enable configUSE\_NEWLIB\_REENTRANT? Because the schedule already be suspend in pvPortMalloc() function.
2. If enable configUSE\_NEWLIB\_REENTRANT, what is \_\_real\_\_malloc\_r() descitped in [FreeRTOS\_helpers/heap\_useNewlib\_ST.c at master · DRNadler/FreeRTOS\_helpers (github.com)](https://github.com/DRNadler/FreeRTOS_helpers/blob/master/heap_useNewlib_ST.c)?  
 ![image](https://d2v6vdsk2p900z.cloudfront.net/original/2X/b/b90228c18cb40436c1a2d132003439ae4dcfc41c.png)  
Is the \_\_real\_\_malloc\_r() equal to pvPortMalloc()?

BRs  
Yao

---

<div class="post-metadata">

**Author:** ![richard-damon](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/richard-damon/32/38_2.png) [@richard-damon](https://forums.freertos.org/u/richard-damon)\
**Post date:** [January 24, 2024, 2:07pm UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/2 "2024-01-24T14:07:14Z")

</div>

Trying to write your own version of malloc to make it “thread-safe” is not guaranteed to work, as library functions that want to use the malloc facilities do not need to actually call malloc, but can use an internal function that provides that capability, thus the link ability to wrap malloc is not guaranteed to work. With newlib, if it was properly configured, you can just define functions \_\_malloc\_lock and \_\_malloc\_unlock to make it thread safe like:

```auto

void __malloc_lock(struct _reent* reent) {
	(void) reent;
	vTaskSuspendAll();
}

void __malloc_unlock(struct _reent* reent) {
	(void) reent;
	xTaskResumeAll();
}

This needs to be either in a .c file or wrapped with an extern "C" { if in a .cpp file

```

---

<div class="post-metadata">

**Author:** ![richard-damon](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/richard-damon/32/38_2.png) [@richard-damon](https://forums.freertos.org/u/richard-damon)\
**Post date:** [January 24, 2024, 2:25pm UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/3 "2024-01-24T14:25:25Z")

</div>

And to answer your more detailed question, \_\_malloc\_r is the actual function that newlib uses to do the function of malloc (and the function malloc() just calles malloc\_r.

\_\_real\_\_malloc\_r is the name the linker provides to your \_\_wrap\_\_malloc\_r to let it access the original code of \_\_malloc\_r in your wrapper.

I would be wary of that code, as \_\_real\_\_malloc\_r should be defined with the same parameters as \_\_wrap\_\_malloc\_r, since that IS the prototype for that function.

---

<div class="post-metadata">

**Author:** ![hs2](https://avatars.discourse-cdn.com/v4/letter/h/a4c791/32.png) [@hs2](https://forums.freertos.org/u/hs2)\
**Post date:** [January 24, 2024, 4:02pm UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/4 "2024-01-24T16:02:21Z")

</div>

Same applies to `free` as you surely know but also to `realloc` and `calloc` which should be wrapped as well. At least that was the case when I verified the newlib sources time ago.

---

<div class="post-metadata">

**Author:** ![richard-damon](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/richard-damon/32/38_2.png) [@richard-damon](https://forums.freertos.org/u/richard-damon)\
**Post date:** [January 24, 2024, 4:12pm UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/5 "2024-01-24T16:12:02Z")

</div>

The simpler thing is to define the \_\_malloc\_lock/unlock instead of wrapping, since FreeRTOS doesn’t provide a realloc equivalent.

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [January 24, 2024, 5:33pm UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/6 "2024-01-24T17:33:12Z")

</div>

There is a library that replaces all `[vsn]printf()` functions. These alternative functions are interrupt safe, they do not use any heap, and they have a very low stack usage. See [printf-stdarg.c](https://github.com/htibosch/freertos_plus_projects/blob/master/plus/Framework/Utilities/printf-stdarg.c).

The only downsize is that the module doesn’t properly support floating point formats.

---

<div class="post-metadata">

**Author:** ![dnadler](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/dnadler/32/35_2.png) [@dnadler](https://forums.freertos.org/u/dnadler)\
**Post date:** [January 31, 2024, 12:41am UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/7 "2024-01-31T00:41:10Z")

</div>

The wrap\_\* functions are for debugging your malloc calls, used with the linker wrap function. Look up and study “gcc linker --wrap” and study the comments a few lines prior to the code you pictured above!  
Hope that helps,  
Best Regards, Dave

---

<div class="post-metadata">

**Author:** ![dnadler](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/dnadler/32/35_2.png) [@dnadler](https://forums.freertos.org/u/dnadler)\
**Post date:** [January 31, 2024, 12:43am UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/8 "2024-01-31T00:43:52Z")

</div>

Richard is correct, I forgot to upload a fix to github, code above should read

```auto
  void * __wrap__ malloc_r(void *reent, size_t nbytes) {
    (void)(reent);
    extern void * __real__ malloc_r(void *reent, size_t nbytes);
    if(!inside_malloc) {
      MallocCallCnt++;
      TotalMallocdBytes += nbytes;
    }
    void *p = __real__ malloc_r(reent, nbytes);
    return p;
  }

```

I’ll try to find time to update the repository…

---

<div class="post-metadata">

**Author:** ![dnadler](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/dnadler/32/35_2.png) [@dnadler](https://forums.freertos.org/u/dnadler)\
**Post date:** [January 31, 2024, 1:49am UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/9 "2024-01-31T01:49:18Z")

</div>

Repository updated, sorry about that, Thanks Richard for pointing this out…

---

<div class="post-metadata">

**Author:** ![danielglasser](https://avatars.discourse-cdn.com/v4/letter/d/5daacb/32.png) [@danielglasser](https://forums.freertos.org/u/danielglasser)\
**Post date:** [February 6, 2024, 11:23pm UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/10 "2024-02-06T23:23:02Z")

</div>

It was my impression that `configUSE_NEWLIB_REENTRANT` changes whether the TCB has the `reent` pointer to provide a place for the `..._r()` functions to put thread/task specific information (states, etc.) instead of using a single structure shared across all tasks/threads. Usually, to get a reentrant `malloc()` (or any other allocator), either each task needs its own pool or there needs to be a global lock or critical section around the free pool walking/defragmenting/freeing/reserving/splitting/etc. This can be a very long process. On some systems, the memory pool is allocated to each task/process from the system heap in larger chunks using functions with names like `brk()` and`sbrk()`; those have a small critical section and once the task “owns” the chunk, the allocators such as `malloc()`, `calloc()`, `realloc()` and `free()` work using an allocator heap made up of chunks that no other task will be managing. When the allocators need more memory to satify a request, they get another chunk from the OS. When the task exits, the OS puts the chunks it had reserved for the task back into its heap, making them available for other tasks/processes. I’m pretty sure that FreeRTOS does not have this sophisticated behavior because it’s hard and overkill for most embedded applications.

---

<div class="post-metadata">

**Author:** ![dnadler](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/dnadler/32/35_2.png) [@dnadler](https://forums.freertos.org/u/dnadler)\
**Post date:** [April 8, 2024, 2:36pm UTC](https://forums.freertos.org/t/reentrant-malloc-function-in-libc-sprintf-type-functions/19020/11 "2024-04-08T14:36:33Z")

</div>

`heap_usenewlib` supports newlib’s use of a single global lock. While it can be slow, presumably most embedded systems of this class are not pounding on free-storage. With `configUSE_NEWLIB_REENTRANT` FreeRTOS does create and clean up requisite task-specific reentrancy blocks on task creation/completion. Hope that’s clear!
