Reallocating memory between internal RAM and PSRAM
Posted: Mon Mar 11, 2024 8:15 pm
I'm writing custom memory allocator for Lua.
The goal is to allocate part of resources in internal RAM, and then use PSRAM after reaching a certain threshold.
Is it safe to re-allocate memory in PSRAM if it was previously allocated in internal RAM (and vice-versa)? Or do I need to track which memory did the allocator use for previous allocation and then call `free` before re-allocating the new segment?
E. g. will this work?
The goal is to allocate part of resources in internal RAM, and then use PSRAM after reaching a certain threshold.
Is it safe to re-allocate memory in PSRAM if it was previously allocated in internal RAM (and vice-versa)? Or do I need to track which memory did the allocator use for previous allocation and then call `free` before re-allocating the new segment?
E. g. will this work?
Code: Select all
void* custom_realloc(void* ptr, uint32_t size) {
// Check if internal RAM will still have at least 32K free memory after reallocation.
// If not - (re)allocate in PSRAM.
uint32_t available = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
uint32_t caps = available - size > 32768 ? MALLOC_CAP_SPIRAM : 0;
return heap_caps_realloc(ptr, size, caps | MALLOC_CAP_8BIT)
}