How to check memory limits

I am trying to check if memory restrictions work in my OS. Therefore, I use this simple c program:

#include <iostream> #include <cstdlib> int main() { const size_t GB = 1024 * 1024 * 1024; const size_t mem = 1 * GB; std::cout << "allocating " << mem << " bytes" << std::endl; void* p = malloc(mem); if (p) { std::cout << "memory allocated" << std::endl; } else { std::cout << "cannot allocate memory" << std::endl; } char a; std::cin >> a; free(p); } 

I am compiling with -O0 , but when I look at the performance monitor, I see that my a.out uses only 128KB. Why can't I see 1 GB?

+4
source share
2 answers

You need to lock the memory. While you are only backing it up, you have allocated "virtual memory". You are reading or writing memory. With your program, just add

 void* p = malloc(mem); if (p) { std::cout << "memory allocated" << std::endl; memset(p, 0, mem); } else { std::cout << "cannot allocate memory" << std::endl; } 

On the Windows operating system, you can use the VirtualQuery function to find out which memory blocks are reserved and what has been done.

+3
source

The OS will only use the "used" memory, which you actually touch, so it will not be displayed on the performance monitor or, for example, when you do not use the "memory". This is due to the fact that some applications allocate large amounts of memory "just in case", and it would take a lot of additional time to actually fill this memory in the process when it is not actually used.

+1
source

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


All Articles