0
  1. I run

    calloc(1024 * 1024 * 1024, sizeof(int));

  2. I check my program's usage and it's zero but I never made a call to free

Edit:

Running Debian Jessie

Edit 2:

I am using the top as the system monitor

Peter Chaula
  • 3,456
  • 2
  • 28
  • 32
  • 1
    please provide more information about your question, such as how did you checked the memory usage, it would help others to understand what you actually means. – oxnz Aug 12 '16 at 19:28
  • Which column did you look at in top ? Are you certain the top program isn't rounding memory usage up/down to the nearest MB or tenths of a MB ? – nos Aug 12 '16 at 19:54
  • So we should guess what are you trying to Code or what? Please show some code – Michi Aug 12 '16 at 20:41

2 Answers2

5

Linux does lazy memory allocation. Only when a page fault occurs on a page marked as allocated does Linux actually consider it as being used. Try writing to a byte inside the allocated data and checking the memory usage again. For more information on memory allocation in Linux, check http://www.tldp.org/LDP/tlk/mm/memory.html.

Additionally, even though calloc zeroes the allocated memory, it can still be done in a lazy way that leads to the behavior you described. See How to lazy allocate zeroed memory?.

mwk
  • 426
  • 7
  • 13
1

Your example only allocates a few K, which may be too small to see. But even if you were to ask for a much larger amount of memory, you won't see usage until you actually use the memory.

Linux by default does not actually allocate memory pages until you touch them somehow. Although calloc is supposed to initialize the memory to zero, this does not count as touching it as internally keeps track of uninitialized pages and returns zeros when read.

wojtow
  • 864
  • 5
  • 11
  • 1
    But `calloc` initialises the memory. – Peter Chaula Aug 12 '16 at 19:33
  • See mwk's answer. calloc claims to initialize memory, but as an optimization on modern linux platforms, it just takes advantage of the fact that newly allocated virtual memory is already zero'd. You essentially can get already zero'd memory by using malloc on such a platform, but as good practice should always call calloc when expecting to have zero'd memory since your code may be ported or run on a different platform where this isn't true. – wojtow Aug 12 '16 at 19:57
  • Oh, I see Thanks dude – Peter Chaula Aug 12 '16 at 19:59
  • It all makes sense now. Seems like malloc only allocates virtual pages without corresponding frames in the page table. – Peter Chaula Aug 07 '21 at 17:30