<p>We've occasionally been getting problems whereby our long-running server processes (running on Windows Server 2003) have thrown an exception due to a memory allocation failure.  Our suspicion is these allocations are failing due to memory fragmentation.</p>

<p>Therefore, we've been looking at some alternative memory allocation mechanisms that may help us and I'm hoping someone can tell me the best one:</p>

<p>1) Use Windows <a href="http://msdn.microsoft.com/en-us/library/aa366750.aspx" rel="noreferrer">Low-fragmentation Heap</a></p>

<p>2) jemalloc - as used in <a href="http://en.wikipedia.org/wiki/Mozilla_Firefox_3" rel="noreferrer">Firefox 3</a></p>

<p>3) Doug Lea's <a href="http://g.oswego.edu/" rel="noreferrer">malloc</a> </p>

<p>Our server process is developed using cross-platform C++ code, so any solution would be ideally cross-platform also (do *nix operating systems suffer from this type of memory fragmentation?). </p>

<p>Also, am I right in thinking that LFH is now the default memory allocation mechanism for Windows Server 2008 / Vista?...  Will my current problems "go away" if our customers simply upgrade their server os?</p>

[{'answer_id': 60876, 'author': 'nsanders', 'author_id': 1244, 'author_profile': 'https://Stackoverflow.com/users/1244', 'pm_score': 1, 'selected': False, 'text': "<p>I'd suspect a leak before suspecting fragmentation.  </p>\n\n<p>For the memory-intensive data structures, you could switch over to a re-usable storage pool mechanism.  You might also be able to allocate more stuff on the stack as opposed to the heap, but in practical terms that won't make a huge difference I think.</p>\n\n<p>I'd fire up a tool like valgrind or do some intensive logging to look for resources not being released.</p>\n"}, {'answer_id': 60886, 'author': 'Fire Lancer', 'author_id': 6266, 'author_profile': 'https://Stackoverflow.com/users/6266', 'pm_score': 2, 'selected': False, 'text': "<p>You can help reduce fragmentation by reducing the amount you allocate deallocate.</p>\n\n<p>e.g. say for a web server running a server side script, it may create a string to output the page to. Instead of allocating and deallocating these strings for every page request, just maintain a pool of them, so your only allocating when you need more, but your not deallocating (meaning after a while you get the situation you not allocating anymore either, because you have enough)</p>\n\n<p>You can use _CrtDumpMemoryLeaks(); to dump memory leaks to the debug window when running a debug build, however I believe this is specific to the Visual C compiler. (it's in crtdbg.h)</p>\n"}, {'answer_id': 60891, 'author': 'Alan', 'author_id': 2958, 'author_profile': 'https://Stackoverflow.com/users/2958', 'pm_score': 1, 'selected': False, 'text': '<p>@nsaners - I\'m pretty sure the problem is down to memory fragmentation.  We\'ve analyzed <a href="http://msdn.microsoft.com/en-us/library/bb204861(VS.85).aspx" rel="nofollow noreferrer">minidumps</a> that point to a problem when a large (5-10mb) chunk of memory is being allocated.  We\'ve also monitored the process (on-site and in development) to check for memory leaks - none were detected (the memory footprint is generally quite low).</p>\n'}, {'answer_id': 60915, 'author': 'maccullt', 'author_id': 4945, 'author_profile': 'https://Stackoverflow.com/users/4945', 'pm_score': 1, 'selected': False, 'text': '<p>The problem does happen on Unix, although it\'s usually not as bad.</p>\n\n<p>The Low-framgmentation heap helped us, but my co-workers swear by <a href="http://www.microquill.com/" rel="nofollow noreferrer">Smart Heap</a>\n(it\'s been used cross platform in a couple of our products for years). Unfortunately due to other circumstances we couldn\'t use Smart Heap this time.</p>\n\n<p>We also look at block/chunking allocating and trying to have scope-savvy pools/strategies, i.e., \nlong term things here, whole request thing there, short term things over there, etc.</p>\n'}, {'answer_id': 60966, 'author': 'dicroce', 'author_id': 3886, 'author_profile': 'https://Stackoverflow.com/users/3886', 'pm_score': 1, 'selected': False, 'text': "<p>As usual, you can usually waste memory to gain some speed.</p>\n\n<p>This technique isn't useful for a general purpose allocator, but it does have it's place.</p>\n\n<p>Basically, the idea is to write an allocator that returns memory from a pool where all the allocations are the same size. This pool can never become fragmented because any block is as good as another. You can reduce memory wastage by creating multiple pools with different size chunks and pick the smallest chunk size pool that's still greater than the requested amount. I've used this idea to create allocators that run in O(1). </p>\n"}, {'answer_id': 61061, 'author': 'Tall Jeff', 'author_id': 1553, 'author_profile': 'https://Stackoverflow.com/users/1553', 'pm_score': 6, 'selected': True, 'text': "<p>First, I agree with the other posters who suggested a resource leak. You really want to rule that out first.</p>\n\n<p>Hopefully, the heap manager you are currently using has a way to dump out the actual total free space available in the heap (across all <strong>free</strong> blocks) and also the total number of blocks that it is divided over. If the average free block size is relatively small compared to the total free space in the heap, then you do have a fragmentation problem. Alternatively, if you can dump the size of the largest free block and compare that to the total free space, that will accomplish the same thing. The largest free block would be small relative to the total <strong><em>free</em></strong> space available across all blocks if you are running into fragmentation.</p>\n\n<p>To be very clear about the above, in all cases we are talking about <strong><em>free</em></strong> blocks in the heap, not the allocated blocks in the heap. In any case, if the above conditions are not met, then you <em>do</em> have a leak situation of some sort.</p>\n\n<p>So, once you have ruled out a leak, you could consider using a better allocator. <strong><em>Doug Lea's malloc</em></strong> suggested in the question is a very good allocator for general use applications and very robust <em>most</em> of the time. Put another way, it has been time tested to work very well for most any application. However, no algorithm is ideal for <em>all</em> applications and any management algorithm approach can be broken by the right pathelogical conditions against it's design.</p>\n\n<p><em>Why are you having a fragmentation problem?</em> - Sources of fragmentation problems are <em>caused</em> by the behavior of an application and have to do with greatly different allocation lifetimes in the same memory arena. That is, some objects are allocated and freed regularly while other types of objects persist for extended periods of time all in the same heap.....think of the longer lifetime ones as poking holes into larger areas of the arena and thereby preventing the coalesce of adjacent blocks that have been freed.</p>\n\n<p>To address this type of problem, the best thing you can do is logically divide the heap into sub arenas where the lifetimes are more similar. In effect, you want a transient heap and a persistent heap or heaps that group things of similar lifetimes.</p>\n\n<p>Some others have suggested another approach to solve the problem which is to attempt to make the allocation sizes more similar or identical, but this is less ideal because it creates a different type of fragmentation called internal fragmentation - which is in effect the wasted space you have by allocating more memory in the block than you need. </p>\n\n<p>Additionally, with a good heap allocator, like Doug Lea's, making the block sizes more similar is unnecessary because the allocator will already be doing a power of two size bucketing scheme that will make it completely unnecessary to artificially adjust the allocation sizes passed to malloc() - in effect, his heap manager does that for you automatically much more robustly than the application will be able to make adjustments.</p>\n"}, {'answer_id': 61067, 'author': 'Mark', 'author_id': 4405, 'author_profile': 'https://Stackoverflow.com/users/4405', 'pm_score': 3, 'selected': False, 'text': '<p>As you suggest, Doug Lea\'s malloc might work well.  It\'s cross platform and it has been used in shipping code.  At the very least, it should be easy to integrate into your code for testing.</p>\n\n<p>Having worked in fixed memory environments for a number of years, this situation is certainly a problem, even in non-fixed environments.  We have found that the CRT allocators tend to stink pretty bad in terms of performance (speed, efficiency of wasted space, etc).  I firmly believe that if you have extensive need of a good memory allocator over a long period of time, you should write your own (or see if something like dlmalloc will work).  The trick is getting something written that works with your allocation patterns, and that has more to do with memory management efficiency as almost anything else.</p>\n\n<p>Give dlmalloc a try.  I definitely give it a thumbs up.  It\'s fairly tunable as well, so you might be able to get more efficiency by changing some of the compile time options.</p>\n\n<p>Honestly, you shouldn\'t depend on things "going away" with new OS implementations.  A service pack, patch, or another new OS N years later might make the problem worse.  Again, for applications that demand a robust memory manager, don\'t use the stock versions that are available with your compiler.  Find one that works for <em>your</em> situation.  Start with dlmalloc and tune it to see if you can get the behavior that works best for your situation.</p>\n'}, {'answer_id': 195330, 'author': 'Tal', 'author_id': 11287, 'author_profile': 'https://Stackoverflow.com/users/11287', 'pm_score': 4, 'selected': False, 'text': '<p>I think you’ve mistakenly ruled out a memory leak too early.\nEven a tiny memory leak can cause a severe memory fragmentation.</p>\n\n<p>Assuming your application behaves like the following:<br>\nAllocate 10MB<br>\nAllocate 1 byte<br>\nFree 10MB<br>\n(oops, we didn’t free the 1 byte, but who cares about 1 tiny byte)</p>\n\n<p>This seems like a very small leak, <strong>you will hardly notice it when monitoring just the total allocated memory size</strong>.\nBut this leak eventually will cause your application memory to look like this:<br>\n.<br>\n.<br>\nFree – 10MB<br>\n.<br>\n.<br>\n[Allocated -1 byte]<br>\n.<br>\n.<br>\nFree – 10MB<br>\n.<br>\n.<br>\n[Allocated -1 byte]<br>\n.<br>\n.<br>\nFree – 10MB<br>\n.<br>\n.<br></p>\n\n<p>This leak will not be noticed... until you want to allocate 11MB<br>\nAssuming your minidumps had full memory info included, I recommend using <a href="http://www.microsoft.com/downloadS/details.aspx?FamilyID=28bd5941-c458-46f1-b24d-f60151d875a3&amp;displaylang=en" rel="noreferrer">DebugDiag</a> to spot possible leaks.\nIn the generated memory report, <strong>examine carefully the allocation count (not size)</strong>.</p>\n'}, {'answer_id': 40864404, 'author': 'Danil', 'author_id': 2165280, 'author_profile': 'https://Stackoverflow.com/users/2165280', 'pm_score': -1, 'selected': False, 'text': "<p>if you talking about Win32 - you can try to squeeze something by using LARGEADDRESSAWARE. You'll have ~1Gb extra defragmented memory so your application will fragment it longer.</p>\n"}, {'answer_id': 53133882, 'author': 'kris2k', 'author_id': 5597891, 'author_profile': 'https://Stackoverflow.com/users/5597891', 'pm_score': -1, 'selected': False, 'text': '<p>The simple, quick and dirty, solution is to split the application into <strong>several process</strong>, you should get fresh HEAP each time you create the process.</p>\n\n<p>Your memory and speed might suffer a bit (swapping) but fast hardware and big RAM should be able to help.</p>\n\n<p>This was old UNIX trick with daemons, when threads did not existed yet. </p>\n'}]
['https://Stackoverflow.com/questions/60871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2958/']