45

Here's my question: Does calling free or delete ever release memory back to the "system". By system I mean, does it ever reduce the data segment of the process?

Let's consider the memory allocator on Linux, i.e ptmalloc.

From what I know (please correct me if I am wrong), ptmalloc maintains a free list of memory blocks and when a request for memory allocation comes, it tries to allocate a memory block from this free list (I know, the allocator is much more complex than that but I am just putting it in simple words). If, however, it fails, it gets the memory from the system using say sbrk or brk system calls. When a memory is free'd, that block is placed in the free list.

Now consider this scenario, on peak load, a lot of objects have been allocated on heap. Now when the load decreases, the objects are free'd. So my question is: Once the object is free'd will the allocator do some calculations to find whether it should just keep this object in the free list or depending upon the current size of the free list it may decide to give that memory back to the system i.e decrease the data segment of the process using sbrk or brk?

Documentation of glibc tells me that if the allocation request is much larger than page size, it will be allocated using mmap and will be directly released back to the system once free'd. Cool. But let's say I never ask for allocation of size greater than say 50 bytes and I ask a lot of such 50 byte objects on peak load on the system. Then what?

From what I know (correct me please), a memory allocated with malloc will never be released back to the system ever until the process ends i.e. the allocator will simply keep it in the free list if I free it. But the question that is troubling me is then, if I use a tool to see the memory usage of my process (I am using pmap on Linux, what do you guys use?), it should always show the memory used at peak load (as the memory is never given back to the system, except when allocated using mmap)? That is memory used by the process should never ever decrease(except the stack memory)? Is it?

I know I am missing something, so please shed some light on all this.

Experts, please clear my concepts regarding this. I will be grateful. I hope I was able to explain my question.

3
  • 1
    "It is entirely implementation dependent." Ok, cool, assume that the Linux implementation never returns memory back to the system. Then can i trust the page replacement of the OS to make sure that having a large address space won't cause a problem ? Sep 14, 2009 at 13:25
  • Also i would like to know what happens on Linux implementation i.e what is the behaviour of ptmalloc in the above scenario. Sep 14, 2009 at 13:25
  • Gist of this post: i am considering writing my own memory pool(on top of general purpose allocator i.e malloc) for the fixed sized objects that are being allocated and deallocated on the heap quite frequently in my application. So that would remove the memory overhead associated with getting an object from malloc and also the allocation and deallocation would be O(1)(amortized). So i was wondering that the Pool should ever give back memory to the general purpose allocator i.e malloc or not. I hope you guys got the gist of the post. Thank you all for replies. I am grateful to you all cheers :) Sep 14, 2009 at 13:36

8 Answers 8

14

There isn't much overhead for malloc, so you are unlikely to achieve any run-time savings. There is, however, a good reason to implement an allocator on top of malloc, and that is to be able to trace memory leaks. For example, you can free all memory allocated by the program when it exits, and then check to see if your memory allocator calls balance (i.e. same number of calls to allocate/deallocate).

For your specific implementation, there is no reason to free() since the malloc won't release to system memory and so it will only release memory back to your own allocator.

Another reason for using a custom allocator is that you may be allocating many objects of the same size (i.e you have some data structure that you are allocating a lot). You may want to maintain a separate free list for this type of object, and free/allocate only from this special list. The advantage of this is that it will avoid memory fragmentation.

2
  • 2
    Is memory fragmentation a problem on systems with virtual memory? Nov 2, 2009 at 4:21
  • 3
    Yes, such fragmentation is in the virtual address space.
    – interfect
    May 23, 2014 at 17:59
7

No.


It's actually a bad strategy for a number of reasons, so it doesn't happen --except-- as you note, there can be an exception for large allocations that can be directly made in pages.

  • It increases internal fragmentation and therefore can actually waste memory. (You can only return aligned pages to the OS, so pulling aligned pages out of a block will usually create two guaranteed-to-be-small blocks --smaller than a page, anyway-- to either side of the block. If this happens a lot you end up with the same total amount of usefully-allocated memory plus lots of useless small blocks.)

  • A kernel call is required, and kernel calls are slow, so it would slow down the program. It's much faster to just throw the block back into the heap.

  • Almost every program will either converge on a steady-state memory footprint or it will have an increasing footprint until exit. (Or, until near-exit.) Therefore, all the extra processing needed by a page-return mechanism would be completely wasted.

5

It is entirely implementation dependent. On Windows VC++ programs can return memory back to the system if the corresponding memory pages contain only free'd blocks.

4

I think that you have all the information you need to answer your own question. pmap shows the memory that is currenly being used by the process. So, if you call pmap before the process achieves peak memory, then no it will not show peak memory. if you call pmap just before the process exits, then it will show peak memory for a process that does not use mmap. If the process uses mmap, then if you call pmap at the point where maximum memory is being used, it will show peak memory usage, but this point may not be at the end of the process (it could occur anywhere).

This applies only to your current system (i.e. based on the documentation you have provided for free and mmap and malloc) but as the previous poster has stated, behavior of these is implmentation dependent.

4

This varies a bit from implementation to implementation.

Think of your memory as a massive long block, when you allocate to it you take a bit out of your memory (labeled '1' below):

111

If I allocate more more memory with malloc it gets some from the system:

1112222

If I now free '1':

___2222

It won't be returned to the system, because two is in front of it (and memory is given as a continous block). However if the end of the memory is freed, then that memory is returned to the system. If I freed '2' instead of '1'. I would get:

111

the bit where '2' was would be returned to the system. The main benefit of freeing memory is that that bit can then be reallocated, as opposed to getting more memory from the system. e.g:

33_2222
5
  • 3
    Memory allocation in modern systems is a bit more complicated than this.
    – Artelius
    Sep 14, 2009 at 13:30
  • I haven't seen this sort of thing before. Do you have a reference? Sep 14, 2009 at 13:31
  • Read up on the system call 'brk'. @Artelius: from the point of view of the application how is it different.
    – Peter
    Sep 14, 2009 at 13:34
  • 2
    BSD manual says "The brk() and sbrk() functions are historical curiosities left over from earlier days before the advent of virtual memory management."
    – Artelius
    Sep 14, 2009 at 13:42
  • 1
    And that page also says that "When allocating blocks of memory larger than MMAP_THRESHOLD bytes, the glibc malloc() implementation allocates the memory as a private anonymous mapping using mmap(2)."
    – Artelius
    Nov 2, 2009 at 4:03
3

I believe that the memory allocator in glibc can return memory back to the system, but whether it will or not depends on your memory allocation patterns.

Let's say you do something like this:

void *pointers[10000];
for(i = 0; i < 10000; i++)
    pointers[i] = malloc(1024);
for(i = 0; i < 9999; i++)
    free(pointers[i]);

The only part of the heap that can be safely returned to the system is the "wilderness chunk", which is at the end of the heap. This can be returned to the system using another sbrk system call, and the glibc memory allocator will do that when the size of this last chunk exceeds some threshold.

The above program would make 10000 small allocations, but only free the first 9999 of them. The last one should (assuming nothing else has called malloc, which is unlikely) be sitting right at the end of the heap. This would prevent the allocator from returning any memory to the system at all.

If you were to free the remaining allocation, glibc's malloc implementation should be able to return most of the pages allocated back to the system.

If you're allocating and freeing small chunks of memory, a few of which are long-lived, you could end up in a situation where you have a large chunk of memory allocated from the system, but you're only using a tiny fraction of it.

1

Here are some "advantages" to never releasing memory back to the system:

  • Having already used a lot of memory makes it very likely you will do so again, and
    • when you release memory the OS has to do quite a bit of paperwork
    • when you need it again, your memory allocator has to re-initialise all its data structures in the region it just received
  • Freed memory that isn't needed gets paged out to disk where it doesn't actually make that much difference
  • Often, even if you free 90% of your memory, fragmentation means that very few pages can actually be released, so the effort required to look for empty pages isn't terribly well spent
1

Many memory managers can perform TRIM operations where they return entirely unused blocks of memory to the OS. However, as several posts here have mentioned, it's entirely implementation dependent.

But lets say I never ask for allocation of size greater than say 50 bytes and I ask a lot of such 50 byte objects on peak load on the system. Then what ?

This depends on your allocation pattern. Do you free ALL of the small allocations? If so and if the memory manager has handling for a small block allocations, then this may be possible. However, if you allocate many small items and then only free all but a few scattered items, you may fragment memory and make it impossible to TRIM blocks since each block will have only a few straggling allocations. In this case, you may want to use a different allocation scheme for the temporary allocations and the persistant ones so you can return the temporary allocations back to the OS.

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.