I'm trying to do an exercise form Stroustrup's C++PL4 book. The task is:
Allocate so much memory using
new
thatbad_alloc
is thrown. Report how much memory was allocated and how much time it took. Do this twice: once not writing to the allocated memory and once writing to each element.
The following code doesn't throw a std::bad_alloc
exception. After I execute the program I get message "Killed" in terminal.
Also. The following code exits in ~4 seconds. But when I uncomment memory usage message
// ++i;
// std::cout << "Allocated " << i*80 << " MB so far\n";
Program will run for few minutes. After some time it prints that terabytes of memory has been allocated but I don't see much change in System Monitor app. Why is that?
I use Linux and System Monitor app to see usages.
#include <iostream>
#include <vector>
#include <chrono>
void f()
{
std::vector<int*> vpi {};
int i {};
try{
for(;;){
int* pi = new int[10000];
vpi.push_back(pi);
// ++i;
// std::cout << "Allocated " << i*80 << " MB so far\n";
}
}
catch(std::bad_alloc){
std::cerr << "Memory exhausted\n";
}
}
int main() {
auto t0 = std::chrono::high_resolution_clock::now();
f();
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(t0-t1).count() << " ms\n";
}