raspberrypi / pico-sdk

BSD 3-Clause "New" or "Revised" License
3.24k stars 837 forks source link

Allow redirecting malloc functions to user defined functions #1716

Open JNTeledyne opened 1 month ago

JNTeledyne commented 1 month ago

I came across a case where we wanted to add custom memory debug/tracking code for malloc. Since pico sdk already wraps malloc we need a way of calling our code from the wrapped pico version of malloc. I had 2 ideas to accomplish this.

  1. Add CMAKE switch to turn off building of pico_malloc so user could implement wrap functions on their own.
  2. Create new PICO_REDIRECT_MALLOC define, if enabled it would replace REAL_FUNC, with REDIRECT_MALLOC_FUNC.

My preference is option 2 as it allows user to still get the functionally in the pico_malloc wrapped functions and just extend it with more functionality.

I have my suggested changes at https://github.com/JNTeledyne/pico-sdk/commit/399cdae0f21a1bb58e709156eeb74a2b002062c6

Another good use of this is if someone wanted to have fun and implement a slab allocator or write their own version of malloc.

JNTeledyne commented 1 month ago

Found issue with my previous change linked above. Here is link with correction.

https://github.com/JNTeledyne/pico-sdk/commit/a495659d3034aa7640c7b1e76d17b45367952c17