Memory allocation and deallocation

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Memory allocation and deallocation

Post by jimmo » Thu Jul 16, 2020 3:44 am

elliotwoods wrote:
Tue Jul 14, 2020 9:47 am
So we can confirm that the GC shouldn't touch memory which is created by the platform's own malloc (e.g. ESP32 heap_caps_malloc).
Something to be aware of if you're using an ESP32 with PSRAM -- MicroPython takes ownership of the PSRAM directly (i.e. outside of ESP32's malloc) and uses it directly for the GC heap (see esp32/main.c). So if you're using heap_caps_malloc to allocate in PSRAM then it's definitely going to be clobbered by the GC.

In general though -- anything you allocate statically or via platform malloc (if you have one, which most ports don't), will not be affected by the GC. As has been pointed out, the main issue is that something you alloc with the GC (i.e. via m_new*) must be referenced in a way that the GC can find (e.g. via the port's root pointers, or the pointer to this alloc must be a member of some other structure that is itself reachable by the GC, e.g. it's a Python object).

User avatar
elliotwoods
Posts: 23
Joined: Wed Dec 04, 2019 8:11 am

Re: Memory allocation and deallocation

Post by elliotwoods » Thu Jul 16, 2020 1:59 pm

Dear all

Thank you so much for clearing this up.

After investigating, I found that another object outside of the heap area that I was investigating was being garbage collected.
I had thought that the API was keeping a copy of this memory, but it was in fact keeping a typecast pointer to the old string which I had passed in from python (which had been correctly... garbage collected!).

I learnt some really useful lessons about memory with Micro Python along the way though.

Post Reply