I am in a scratchbox cross compile 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 any increase in the memory footprint of the process. Why is that?
You probably built very optimized.
On most modern systems gcc knows that malloc returns a non-aliased pointer. That is to say, it will never return the same pointer twice and it will never return a pointer you have saved 'live' somewhere else.
I find this very very hard to imagine, but it is possible that malloc is being called once and its return value being used over and over. The reasons being:
It knows your memory is a dead store. ie: you write to it, but it never gets read from. The pointer is known to not be aliased so it hasn't escaped to be read from somewhere else, and it isn't marked volatile. Your for loop itself /could/ get thrown away.
At that point it could just use the same memory over and over.
Now here is why I find it hard to believe: Just how much does gcc know about malloc? Malloc could have any kind of side effects like incrementing a global 'number of times called' to 'paints my room a random shade of blue'. It seems really weird that it would drop the call and assume it to be side-effect-free. Hell, 'malloc' could be implemented to return NULL every 100th call (maybe not quite to spec, but who is to say).
What it is NOT doing is freeing it on your behalf. That goes beyond what it 'could' know and into the territory of 'doing things it's just not allowed to'. You're allowed to leak memory, lame though it may be.
2 things would be useful here: 1) Compile environmenet: which os, compiler, and command line flags.
and 2) disassembly of the final binary. (objdump or from the compiler)
rss and %mem are both in terms of "physical memory being used by the process at the moment". It has plenty of opportunity to page stuff out. Try adding vsz. I bet that grows as you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With