[英]C++ Unhandled exception for large vector/array
我在代碼中不斷遇到未處理的異常,這讓我感到困惑。
我確信這是我聲明變量的方式。
基本上,我試圖創建3個數組,M行,N列隨機變量。 如果我將N設置為1,000,將M設置為10,000,這不是問題。 如果然后將M更改為100,000,則會出現未處理的異常內存分配錯誤。
有人可以幫我了解為什么會這樣。
部分代碼是在VS2010上編寫的。 我現在進入了VS2013,因此,對使用新功能的任何其他建議也將不勝感激。 干杯,
#include <cmath>
#include <iostream>
#include <random>
#include <vector>
#include <ctime>
#include <ratio>
#include <chrono>
int main()
{
using namespace std::chrono;
steady_clock::time_point Start_Time = steady_clock::now();
unsigned int N; // Number of time Steps in a simulation
unsigned long int M; // Number of simulations (paths)
N = 1000;
M = 10000;
// Random Number generation setup
double RANDOM;
srand((unsigned int)time(NULL)); // Generator loop reset
std::default_random_engine generator(rand()); // Seed with RAND()
std::normal_distribution<double> distribution(0.0, 1.0); // Mean = 0.0, Variance = 1.0 ie Normal
std::vector<std::vector<double>> RandomVar_A(M, std::vector<double>(N)); // dw
std::vector<std::vector<double>> RandomVar_B(M, std::vector<double>(N)); // uncorrelated dz
std::vector<std::vector<double>> RandomVar_C(M, std::vector<double>(N)); // dz
// Generate random variables for dw
for (unsigned long int i = 0; i < M; i++)
{
for (unsigned int j = 0; j < N; j++)
{
RANDOM = distribution(generator);
RandomVar_A[i][j] = RANDOM;
}
}
// Generate random variables for uncorrelated dz
for (unsigned long int i = 0; i < M; i++)
{
for (unsigned int j = 0; j < N; j++)
{
RANDOM = distribution(generator);
RandomVar_B[i][j] = RANDOM;
}
}
// Generate random variables for dz
for (unsigned long int i = 0; i < M; i++)
{
for (unsigned int j = 0; j < N; j++)
{
RANDOM = distribution(generator);
RandomVar_C[i][j] = RANDOM;
}
}
steady_clock::time_point End_Time = steady_clock::now();
duration<double> time_span = duration_cast<duration<double>>(End_Time - Start_Time);
//Clear Matricies
RandomVar_A.clear();
RandomVar_B.clear();
RandomVar_C.clear();
std::cout << std::endl;
std::cout << "its done";
std::cout << std::endl << std::endl;
std::cout << "Time taken : " << time_span.count() << " Seconds" << std::endl << std::endl;
std::cout << "End Of Program" << std::endl << std::endl;
system("pause");
return 0;
}
// *************** END OF PROGRAM ***************
三個100,000 x 1,000的雙打數組表示3億個雙打。 假設8字節加倍,則大約有2.3 GB的內存。 默認情況下,您的進程很可能在Windows上默認限制為2 GB(即使您在計算機上安裝了更多的RAM)。 但是,有一些方法可以使您的進程訪問更大的地址空間: Windows的內存限制 。
我遇到過類似的情況,然后我的32位應用程序分配了超過2Gb的內存。 您的向量需要大約2.1Gb內存,因此可能是相同的問題。 嘗試將應用程序的平台更改為x64。 這樣可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.