This should fill my memory every second with ca 100 MB. I track the memoryusage with gnome-systemmonitor and htop. But somehow it does not. Why?
#include "unistd.h"
#include <iostream>
int main(int argc, char *argv[])
{
while (true){
std::cout << "New one" << std::endl;
new char[100000000];
sleep(1);
}
return 0;
}
To run:
g++ -std=c++11 -O0 main.cpp; ./a.out
Because you're not using it, Linux does lazy allocation so it will not actually map any memory page until you use it.
If you put some code like:
char* test = new char[100000000];
test[0] = 'a';
test[4096] = 'b';
...
You should see it's actually consuming your system memory.
I have only seen clang optimize away calls to new and in general a compiler will not perform such aggressive optimizations when you are using -O0
.
We can see from godbolt that gcc
indeed does not optimize away the call to new
in very similar code:
.L2:
movl $100000000, %edi
call operator new[](unsigned long)
movl $1, %edi
call sleep
jmp .L2
So most likely Paul is correct and lazy allocation is involved and therefore once you write to the allocated memory you will see it being used.
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