Reallocating memory between internal RAM and PSRAM

and3rson
Posts: 2
Joined: Mon Mar 11, 2024 8:03 pm

Reallocating memory between internal RAM and PSRAM

Postby and3rson » 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?

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

ESP_Sprite
Posts: 9052
Joined: Thu Nov 26, 2015 4:08 am

Re: Reallocating memory between internal RAM and PSRAM

Postby ESP_Sprite » Tue Mar 12, 2024 3:15 am

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)

and3rson
Posts: 2
Joined: Mon Mar 11, 2024 8:03 pm

Re: Reallocating memory between internal RAM and PSRAM

Postby and3rson » Tue Mar 12, 2024 9:43 am

Great. Thanks for response and reference!

Who is online

Users browsing this forum: No registered users and 190 guests