Why is the memory size of this program not increasing?

I am in cross scratch compilation environment and have this

#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { int * ptr; int i=0; while(1) { ptr = (int*)malloc( 10485760 * sizeof(int) ); if(ptr == NULL) { printf("Could not malloc\n"); exit(1); } else { printf("Malloc done\n"); for (i = 0 ; i <= 10485759 ; i++) { ptr[i] = i ; } sleep (5); continue; } } } 

When I run the binary and do

 ps -p pid -o cmd,rss,%mem 

I do not see an increase in memory in the process. Why is this?

+6
source share
3 answers

You probably built a very optimized version.

On most modern systems, gcc knows that malloc returns a non-smooth pointer. That is, it will never return the same pointer twice, and it will never return the pointer that you saved live somewhere else.

It is very difficult for me to imagine this, but it is possible that malloc is called once, and its return value is used again and again. Causes:

He knows that your memory is a dead store. i.e.: you write to it, but it is never read. It is known that the pointer is not smoothed, so it did not slip away so that it could be read from another place, and it was not marked unstable. Your for / can / get throw away loop.

At this point, he can use the same memory again and again.

Now here's why it's hard for me to believe: how much does gcc know about malloc? Malloc may have some kind of side effects, such as an increase in the global number of times called "the colors of my room, a random shade of blue." It seems strange that he refused the call and suggested that he had no side effects. Hell, "malloc" can be implemented to return NULL every 100th call (maybe not quite by specification, but who should say).

What he does NOT do is set him free on your behalf. This goes beyond what he “could” know and in the territory “do what he is simply not allowed to do.” You are allowed to seep into memory, limping, although it may be.

2 things would be useful here: 1) Compile the environment: which os, compiler and command line flags.

and 2) disassembling the final binary code. (objdump or from compiler)

+5
source

rss and% mem are like "the physical memory currently in use by the process." It has many possibilities to lay out pages. Try adding vsz. I bet that is growing as you expect.

+2
source

Your compiler helps you free the allocated memory (assuming that the optimized version of your code even comes close to malloc) when it realizes that you are not using it. You can try to print the pointer value (printf ("0x% x", ptr);) - I suspect you will get duplicate values. A more reliable check will lead to the writing of a known bit string into memory, having already seen whether the allocated memory is already in this string. In other words, instead of writing i, write 0xdeadbeef0cabba6e again and again, after checking, to see if this bit pattern is already in the allocated space.

-2
source

Source: https://habr.com/ru/post/916610/