Question

I'm profiling my app, and was trying to see how the app would behave on a low memory situation.

I know that I can simulate the low memory warning using the simulator, but I don't want to simulate how the app will behave if the memory warning is triggered, but instead, see how the app will behave on an actual low memory environment.

To increase the memory usage overtime, I've create a method that calls

char *a = malloc(1024*1024);

And the result is rather interesting. I'm probably reading it wrong, and that's where I would like some help.

On instruments Allocations, at some point I had the app using more than 1GB on "Live Bytes" column, but the app didn't crash running on a real device and worked fine.

live bytes screenshot

Looking at Resident/Dirty size, on VM Tracker, I had a different result, about 134mb on resident and 78mb on dirty size.

resident size screenshot

What am I missing here? According to the docs:

Live Bytes : The number of bytes that have been allocated, but not released.

Resident Size: The amount of actual memory being used.

Why are results so different? Thanks

Was it helpful?

Solution

A bit tricky here. I ran some tests. A couple of comments:

1- You should always typecast the allocated memory:

char *a = (char*) malloc(1024*1024);

2- If you are allocating 1MB above and I see 1GB in the live bytes, this tells me you are using a for loop (1000 times) like this:

for (int i=0; i<1000; ++i)
{
   char* a =  malloc(1024*1024);
}

It looks like even though you are allocating 1GB of space and not freeing it; it is showing correctly in instruments - but it is not effectively causing a memory crash because this 1GB space has nothing stored in it. It looks like the compiler might be doing some optimization and ignoring this 1GB and as such there is no memory crash.

3- If you change your code to:

  for (int i=0; i<1000; ++i)
{
    char* a =  (char*) malloc(1024*1024);
    memset(a, 'b', 1024*1024);
}

Here you are just allocating the character 'b' to every byte in the 1GB space. This will cause a memory crash. So my conclusion is that the compiler optimizes empty mallocs.

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top