0

I'm trying to free memory after pointers array as in a following code:

int ** t = (int**) malloc(sizeof(int*)*10000000);
printf("1\n");
getchar();
for(int i =0; i < 10000000; i++){
    t[i] = (int*) malloc(sizeof(int));
    *t[i] = i;
}
printf("2\n");
getchar();

for(int i =0; i < 10000000; i++){
    free(t[i]);
}
printf("3\n");
getchar();

free(t);
printf("4\n");
getchar();

During the execution my system monitor shows me some strange values. When specific numbers are displayed (as in the code) i get following memory usage.

  1. 148K
  2. 390,540K
  3. 390,540K
  4. 312,676K

I'm a bit confused. Why numbers in 2 and 3 are the same? Am I doing something wrong, or system monitor is inaccurate? If it is fault of SM then why it noticed difference between 3 and 4?

dulef123
  • 1
  • 1
  • 3
    On a virtual memory system, the system tends not to commit pages until you actually use the memory. And `free` tends not to return memory to the OS. – Steve Summit Apr 25 '18 at 16:07
  • " i get following memory usage" - from *where* ?? Taskman ?? The sub-allocator for your implementation may be keeping the memory in a free list, still allocated from the OS, but ready for another round of (now much faster) allocations. – WhozCraig Apr 25 '18 at 16:07
  • 2
    The memory has been released to the heap, but the heap may not have released it to the system. It doesn't have to. – Paul Ogilvie Apr 25 '18 at 16:18
  • if you on linux run your program under valgrind. That will really tell you if the memory is released or not – pm100 Apr 25 '18 at 17:08
  • Welcome to Stack Overflow! [Do I cast the return of malloc ?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858) – Stargateur Apr 25 '18 at 17:10

1 Answers1

1

The behavior of free() depend on its underlying implementation. Most of the implementations of free()does not return the freed memory back to the OS but just gives the memory back to the pool, from which the malloc requests are satisfied, which simply means the freed memory is now available to reuse by the program. Check this.

H.S.
  • 11,654
  • 2
  • 15
  • 32