Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange iOS memory allocation behavior

I noticed quite a strange thing while trying to allocate a lot of memory on my iPhone 3G running iOS 4.2.1.

When I call malloc(512 * 1024) in a loop it returns a valid pointer for about 1500 times after which I get a NULL and

app(2032,0x3e7518b8) malloc: *** mmap(size=524288) failed (error code=12)
*** error: can't allocate region 

It surprised me, since I think my iPhone doesn't 750 MB of RAM. Then I added a memset after the malloc and it brought the number of allocations down to 120, which makes much more sense.

Here's the super-simple code that I used:

for (int i = 1; ; ++i)
{
    void *p = malloc(512 * 1024);
    NSLog(@"%d %p", i, p);
    memset(p, 0, 512 * 1024);
}

I though iPhone didn't have any virtual memory system that could explain behavior similar to this. What would be a reasonable explanation for this?

like image 792
detunized Avatar asked Feb 01 '11 21:02

detunized


2 Answers

On iOS (and many other systems), a call to malloc() doesn't actually allocate memory. It requests memory from the OS/kernel, but the request is not satisfied until the memory is written to (e.g. with memset().) This allows for greater efficiency in the system's memory management, but it can result in misleading malloc() behaviour.

like image 92
Jonathan Grynspan Avatar answered Nov 12 '22 16:11

Jonathan Grynspan


The iPhone definitely has a virtual memory system. What it's missing is the ability to page memory out to disk. In other words, it's missing swap space.

like image 34
Lily Ballard Avatar answered Nov 12 '22 17:11

Lily Ballard