问题
A homework assignment I am working on requires that we exhaust our main memory so that the program uses virtual memory so that we can observe and measure the slowdown. However, when I get to sufficiently large memory values, I segfault or crash. I need to exhaust main memory and use virtual memory simultaneously and I was under the impression that windows (or other operating systems) would just take care of this, at least that is how it has been portrayed to me. The program I am using to observe this:
#include <stdio.h>
#include <iostream>
#include <chrono>
int sizes[] = { 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 };
using namespace std::chrono;
int main(int c, char** args)
{
int** A;
int** B;
int** C;
for (int n : sizes)
{
A = new int*[n];
B = new int*[n];
C = new int*[n];
for (int i = 0; i < n; i++) {
A[i] = new int[n];
B[i] = new int[n];
C[i] = new int[n];
}
milliseconds pre_add1 = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
milliseconds post_add1 = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
milliseconds pre_add2 = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n; i++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
milliseconds post_add2 = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
for (int i = 0; i < n; i++) {
delete A[i];
delete B[i];
delete C[i];
}
delete A;
delete B;
delete C;
std::cout << "Size " << n << " took " << (post_add1 - pre_add1).count() << " ms for addition 1" << std::endl;
std::cout << "Size " << n << " took " << (post_add2 - pre_add2).count() << "ms for addition 2" << std::endl;
}
return 0;
}
回答1:
Every call to new should have a corresponding call to delete and every call to new[]
should have a corresponding call to delete[]
.
By instead calling delete
on a memory block that was allocated with new[]
, you are causing undefined behavior. This is likely the reason for your crash.
To fix the problem, you must change the lines
delete A[i];
delete B[i];
delete C[i];
to
delete[] A[i];
delete[] B[i];
delete[] C[i];
and the lines
delete A;
delete B;
delete C;
to
delete[] A;
delete[] B;
delete[] C;
Also, you may want to increase the size of your page file, so that new
doesn't fail so quickly. For Windows 7, see this link on how to increase the page file size.
来源:https://stackoverflow.com/questions/60940176/c-program-not-relying-on-virtual-memory