Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new does not allocate memory

Tags:

c++

memory

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  
like image 526
ManuelSchneid3r Avatar asked Dec 25 '22 20:12

ManuelSchneid3r


2 Answers

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.

like image 58
Mine Avatar answered Jan 16 '23 07:01

Mine


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.

like image 45
Shafik Yaghmour Avatar answered Jan 16 '23 06:01

Shafik Yaghmour