Subject: bug#45200: Memory leaks: (garbage-collect) fails to reclaim memory

From: Eli Zaretskii <[email-masked]>
Date: Sun, 13 Dec 2020 00:53:57 -0500

> From: Konstantin Kharlamov <[email-masked]>
> Cc: [email-masked]
> Date: Sun, 13 Dec 2020 01:44:13 +0300
> 
> Alright, fair enough. I crafted up another testcase, it may be better. The following code first temporarily disables GC, then it prints "hello" 1000000 times, and finally it calls GC manually.
> 
> I call `emacs -Q`, then measure PSS, then evaluate the code below, then again measure PSS.
> 
>     (let ((i 1000000))
>       (setq gc-cons-threshold most-positive-fixnum)
>       (while (> i 0)
>         (print "hello")
>         (setq i (- i 1)))
>       (garbage-collect))
> 
> The loop takes 20-30 seconds for me, I think. PSS before is ≈41M, and PSS after is 266.3M. That is ≈200M of memory just vanished.

That memory hasn't vanished, it is in your libc's malloc arena,
available for future allocations.  When and if it will be given back
to the OS is up to the specifics of the malloc implementation.  E.g.,
when I do the above on MS-Windows, where malloc is more eager to return
memory to the OS, I end up with just 40 MB footprint, and if I then
invoke GC manually, the memory goes down almost to the original value:
14 MB vs 12 MB after startup.

There are many places on the Internet which explain why the memory
footprint of a program doesn't go back to the original value even
though the program frees all the heap memory it allocated.  I suggest
to read some of those explanations.

> Regarding, whether it is stack size:
> 
>      λ grep VmStk /proc/283047/status
>     VmStk:       132 kB
> 
> Apparently, it is not stack size.

This is a misunderstanding.  The space allocated for the stack doesn't
need to grow.  Values are pushed and popped there depending on the
callstack depth, and Emacs regards anything on the stack that looks
like a Lisp value or a pointer to a Lisp value as an indication that
this Lisp value is in use, and shouldn't be GC'd.