3

So, this is what I'm trying to do :

  • Free up system memory (inactive memory), in the same fashion the purge command does, though programmatically.

I've tried the code here (which its author claims it works), but all it does is to cause Mac OS X to freeze :

void
free_up_memory()
{
    int c;
    char *p, *q;

    for(c = 0; c < 2048; c++)
    {
        if(!(p = malloc(1024 * 1024)))
        {

            return;
        }
        for(q = p; q < p + (1024 * 1024); q += 4096)
        {
            *q = 1;
        }

    }
}

Any ideas?

2
  • 1
    link to 'its author' and an explanation might be nice? Sep 5, 2012 at 8:41
  • 8
    oh, and why do you want to free memory - if it's inactive won't OSX give it you when you ask for it anyway (this isn't a sarky comment, I'm actually interested :) Sep 5, 2012 at 8:42

5 Answers 5

23

The reality is that code is not doing -- and will never do -- what it claims. It is garbage.

All it is going to do is undermine the system's buffer caching subsystem and likely drive the machine into paging rapidly, causing symptoms that look entirely like a lockup. Especially on a system with a slow (5,400rpm laptop drive, for example) hard drive.

At least, on systems with relatively small amounts of RAM. On systems with larger amounts of RAM and relatively light load of apps running, that program is going to evict 2GB of buffer caches, causing various I/O operations to be slower as various things need to be re-read from disk, and not really help anything.

Nor should any such thing be necessary; if an app needs memory, the system will evict pages from the buffer caches and/or page out memory to disk as needed (on OS X -- on iOS there is no pager capable of writing dirty pages largely to preserve responsiveness).

Calling out to purge will evict the various disk buffer caches and simulate conditions at a cold boot, but -- again -- that just undermines the system's caching mechanisms without actually increasing performance for user level apps. As the man page documents, it can be quite useful for testing app performance in a cold cache state, but even that is a bit dubious in that purge won't evict everything that can be evicted; won't cleanly simulate a cold state.

To Steve Jessep's quite valid point, there may be situations where a call to purge (or the like) might increase performance in that case. This typically -- almost universally -- falls apart in the general case in that there is no way for user process A to know what user processes B,C,D,....,Z might do at any point in the near or distant future. Example; A might go and purge stuff only to have RSS Feed Scraper R rip down a few MB of XML to be parsed and persisted, immediately invalidating the purge. Worse, R's last refresh may have had bits still lurking in the cache such that R's refresh pounds on I/O making it both slower and more costly (including costing battery life).

2
  • I know the OS is supposed to handle inactive memory intelligently, but I have consistently seen time and time again that when memory usages is nearly 100% that the system slows to a crawl even though there are several gigabytes of inactive memory. 10.7 and 10.8 just don't seem to handle this situation well. Running purge slows it down even further for a moment, but once purge exits the system instantly snaps back to what feels like full speed. The 10.9 previous seem to handle this a lot better, probably due to the memory compression feature. Aug 15, 2013 at 6:05
  • Why does the OS have such a hard time in low-memory situations with gigabytes of inactive memory? Inactive RAM is just caches of stuff from disk, is it not? Shouldn't it be able to free that memory up nearly instantly? Perhaps I should just post this as a question rather than a comment. Aug 15, 2013 at 6:06
6

What this code actually does is allocate as much memory as it can up to 2GB in 1MB chunks and write some data to it to ensure that the memory is actually committed. That is, to ensure you aren't just assigned virtual address space but no memory. Then it leaks it.

So, what the code does is "force the OS to do what it does when it runs out of memory". Then when this program exits, its memory is freed and you have lots of nice free space.

The author of this code is hoping that "what the OS does when it runs out of memory" is to release what you're calling "inactive memory". It looks like what it actually does for you is freeze. Obviously that's a bug. There are any number of devices and services running at any one time, and only one of them needs to be defective to cause problems. For the OS to freeze, the problem has to be something running in higher than user mode, so I'm disappointed but not really surprised.

14
  • 1
    I doubt the system is freezing. It is likely in swap death, paging out so much memory that disk I/O makes it appear to be wedged. Disks are damned slow compared to memory. Overall, though, what OP is doing is a waste of time.
    – bbum
    Sep 5, 2012 at 12:38
  • 1
    @bbum: I'm talking the questioner's word for it that the system is freezing. If it's not, they can ask another question ;-) But if it doesn't move after (say) 3 hours then I'd probably call it frozen even if the disk is showing activity, since that's far longer than it ought to take to shovel 2GB of data in and out of swap a few times. Sep 5, 2012 at 13:50
  • 1
    Yeah -- but, ultimately, we're discussing the fine points of a pile of garbage. That code isn't going to do what OP wants. Calling out to purge might be interesting in a debug environment to see how your app behaves, but that is a mean thing to do to the system, too, in that the system level caches work best when user level code doesn't try to second guess them.
    – bbum
    Sep 5, 2012 at 17:16
  • 1
    @bbum: the people I found advocating purge were the opposite, actually -- very uncontrolled environments but they found that after running some combination of resource-hog apps (different ones for different people), OSX got itself into a sluggish state that purge appeared to fix. One of them specifically said that it was after quitting the apps, OSX would keep failing to run things claiming to be out of memory until they ran purge. Which for me was another case of "disappointed but not entirely surprised". Not in the bay area, but shout if you're ever in Oxford, UK. Our pints are bigger! Sep 6, 2012 at 8:30
  • 1
    It's possible of course that purge didn't fix it, but sitting around for a couple of minutes waiting for purge did fix it, and they were exaggerating the original problem they thought it fixed :-) Sep 6, 2012 at 8:31
4

Mac OS X is probably freezing because it is waiting for the virtual memory manager (VMM) to swap pages out to disk; since your function is rapidly allocating memory, the system is doing everything it can to serve it up, and it's going to use be using the disk swap file before it gives up.

Once this is happening, everything in the system that allocates memory is going to stall while the VMM is swapping pages in and out. Normally this just causes small delays here and there, but since you are sucking up all available memory, almost everything in the system is going to be blocking on disk I/O.

I'm fairly confident if you waited long enough, the VMM would catch up and the system would go back to normal.

You can test my assumption by looking at the Activity Monitor while the app is running; if I'm right, disk I/O will be very high while the Mac is frozen.

If you actually want to free up memory, you should do something different: programmatically execute the purge command, or replace the call to malloc with something that will keep the memory "wired" (won't be paged to disk). Or, don't do this at all, and instead of second-guessing the VMM, just let it do it's job.

1
  • 1
    Test this theory by introducing a sleep into the outer loop -- if the problem is thrashing swap rather than low memory per se, then running the same code slowly will be fine. Sep 5, 2012 at 9:03
3

That program does not execute the same as purge -- it simply tries to simulate the effects of purge. Sometimes this is successful, sometimes it just flushes unnecessary amounts of memory out to disk (which would explain why your programs may be slow when you return to them). purge does something completely different -- it focuses on specific memory.

As far as the 'freeze' yes, once you hit the ceiling, the system will begin pushing the contents of memory out to disk. The system will also attempt to free memory backed file nodes in the process -- memory backed file nodes is specifically what purge focuses on. Your program ends up pushing other processes' memory to disk. It's not a good solution for the problem. It requires too much, and is not selective. Anyways… the approach could squeeze by as working as advertised. It does something kind of similar, and could free disk buffer caches in the process.

FWIW, this is less of a problem in 10.8, than 10.7.

2
  • purge will also not cause swap death (though it'll cause a hell of a lot of read I/Os as the cache buffers refill).
    – bbum
    Sep 5, 2012 at 17:23
  • 1
    @bbum right. purge may result in a sluggish system for a few moments during eviction (+recovery) -- brute force eviction techniques (in OP) can just make the system unusable for several minutes, depending on available memory and what is paged out (+much longer recovery).
    – justin
    Sep 5, 2012 at 18:14
1

This should free up all RAM that OS X deems to not be needed:

-(void)purgeRAM {
    NSTask *purgeTask = [[NSTask alloc] init];
    [purgeTask setLaunchPath:@"/usr/bin/purge"];
    [purgeTask launch];
    [purgeTask waitUntilExit];
    NSLog(@"Purge complete");
}
4
  • 1
    I tried it and I ve got exception launch path is not accesible May 23, 2014 at 16:24
  • launch path not accessible
    – Giau Huynh
    Feb 3, 2015 at 10:04
  • Take note that the answer is from 2013, When I had a mac it wasn't running the latest and greatest OS X that's out today. Feb 3, 2015 at 16:09
  • For future readers, purge resides in /usr/sbin in later macOS versions => which purge => /usr/sbin/purge
    – Will
    Aug 12, 2020 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.