Page 1 of 1

Reallocating memory between internal RAM and PSRAM

Posted: Mon Mar 11, 2024 8:15 pm
by and3rson
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?

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)
}

Re: Reallocating memory between internal RAM and PSRAM

Posted: Tue Mar 12, 2024 3:15 am
by ESP_Sprite
Yes. heap_caps_realloc will check if if the caps of the allocated space are compatible with the requested caps and will try reallocating in place if that is the case, but if not it'll go through an alloc->memcpy->free dance to get the memory reallocated (ref)

Re: Reallocating memory between internal RAM and PSRAM

Posted: Tue Mar 12, 2024 9:43 am
by and3rson
Great. Thanks for response and reference!