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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With