So I have this program that allocates 256 MB of memory, and after the user presses ENTER it frees the memory and terminates.
#include <stdio.h> #include <stdlib.h> int main(void) { char *p, s[2]; p = malloc(256 * 1024 * 1024); if ( p == NULL) exit(1); printf("Allocated"); fgets(s, 2, stdin); free(p); return 0; } I ran this program multiple times and backgrounded each of them until there is no longer enough memory that can be allocated. However, that never happens. I ran a linux top command and even after running this program many times, the free memory never goes down by nearly as much as 256 MB.
However, on the other hand, if I use calloc instead of malloc then there is a HUGE difference:
p = calloc(256 * 1024 * 1024, 1);
Now if I run the program and background it, and repeat, every time I run it, the free memory goes down by 256 MB. Why is this? Why does malloc not cause the available free memory to change, but calloc does?
malloc, the computer doesn't need to actually give it to you yet. Withcallocthough, the memory needs to be used (for the zeroing out part), and hence the computer actually needs to give you all of it.topandfreecommands' "free memory" figures are meaningless. At best they're telling you about cache efficiency. The actual meaningful number, commit charge, can be found in/proc/meminfoas theCommitted_AS:line.callocimplementations – but Ryan is apparently using one of those. BSD omalloc, for example, does not usually access the memory.