Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android NDK: what happens to memory allocated with malloc when app finishes?

I have some routines writen in C which are called from inside a Java class with the NDK

In these routines, I use mallocs just at the beginning to set up some internal arrays which are used later in calls to the C routines. These arrays are defined globally in the C part, but not linked or referenced anyhow on the Java side

My question is, when my app is closed, must i bother to free this memory or does the system automatically free it? I mean, is the system somehow aware that those allocations were made from a class that is being destroyed so automatically also clears it, or this is not the case?

like image 358
Jordi C. Avatar asked Dec 06 '25 03:12

Jordi C.


1 Answers

To expand a bit on Peter's answer, your program requests memory from the OS in great big blocks. Those blocks are then used by your program to allocate small amounts for particular data structures. The OS does not have any understanding of those data structures: class instances, arrays or anything else.

When your program terminates, the OS simply declares all the big chunks it gave to your program as "free", to be given out to any other program that requests more memory. Any structure that your program was aware of becomes simply bytes containing meanigless numbers.