I often try to fix bugs that occur when I use my iphone for other memory hungry stuff and it needs to free some memory and thus unload some views from my app. I found this quite hard to simulate when I need it so I decided to make that will try to allocate as much memory as possible and force my tested app to release unused views etc.
I tried something simple as calling this every few hundred milliseconds but it for some reason didn't do anything
[[NSData alloc] initWithBytes:malloc(2048 * 1024) length:2048 * 1024];
Instruments show that apps is getting bigger and bigger, far beyond memory capacity of iphone (hundreds of mbs allocated) but I don't even get memory warning and it doesn't affect other apps at all. Is there some safeguard that somehow prevents iphone app form doing something like this? Or is there some mistake in my assumptions about how iphone works? How do you solve this problem when you face it?
EDIT: I am running my app on device, I wasn't able to get my views unloaded on simulator even if I simulated memory warning (this sometimes work, but only rarely)
EDIT2: as bbum pointed out problem was indeed in virtual allocation, simple memset after allocation did the trick
void *data = malloc(1024 * 1024);
memset(data, 0, 1024 * 1024);
Add more photos At the bottom, tap Photos & Videos. Tap the plus sign on the bottom corner. Select the photos or videos you want, and tap Done when you finish. Tap Done once more and you'll be back on the Edit screen.
Beta versions of iOS 15 and iPadOS 15 now give developers the option of requesting more RAM than the current 5GB maximum per app, with limitations. Apple has always set a cap on how much RAM any one app can use on the iPad, but it's become more of an issue as the devices themselves physically include more.
Most likely, what is happening is a tricksy bit of virtual addressing behind your back.
Namely, an application is free to reserve up to the full 4GB of 32-bit address space available to it (less than 4GB, really, because there is fragmentation caused by various system pieces).
When you do malloc(REALLYBIGNUMBER)
, the system uses vm_allocate()
to fulfill the request. The mach memory manager hands you back the addresses, but doesn't actually back it with real memory (kinda like the US economy has tons of $$$ in the market not backed by any real asset).
Physical memory will only be used when you write (or, technically, read) something to the memory. And it will only happen page by page.
So, if you were to walk through the allocated buffer in strides of 4096 (page size) and write one byte, you'd quickly see real memory being consumed.
Can you not just simulate a memory warning in the simulator using the 'Device' menu?
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