为太多动态分配的数组赋值时程序崩溃 - C++
Program crashes when assigning value to too many dynamically allocated arrays - C++
我的程序中有大约 +30 个动态分配的数组,每个数组的定义如下:
int Nx = 240;
int Ny = 240;
double* array = new double(Nx*Ny);
我可以为其中的 16 个赋值,但是一旦我达到第 17 个,它就会抛出段错误!
这是抛出它的代码,完全没问题!
for (int i = 0; i < Nx*Ny; i++) {
array[i] = 0;
}
我真的不知道为什么,我想到了 运行 out of heap,但是因为我有 4GB 的 RAM 这应该是不可能的!
我在 Windows 10!
上使用 MSVS15 和 运行 程序
知道为什么会这样吗?
确切错误:
Exception thrown at 0x00298389 in ecostress.exe: 0xC0000005: Access violation writing location 0x01D2B000.
If there is a handler for this exception, the program may be safely continued.
简单的错字:
double* array = new double(Nx*Ny); // creates a single, initialized double
double* array = new double[Nx*Ny]; // creates an array of doubles
@Hurkyl 回答正确。
我只是想补充一点,如果是在 C++ 上,那么最好使用向量:
vector<int> array(Nx*Ny);
要直接访问指针,您可以使用 &array[0]
,虽然通常没有理由这样做,但您仍然可以这样做 array[0] = 0
。
vector
和 stl 的优点通常是它通过析构函数自动释放内存。
我的程序中有大约 +30 个动态分配的数组,每个数组的定义如下:
int Nx = 240;
int Ny = 240;
double* array = new double(Nx*Ny);
我可以为其中的 16 个赋值,但是一旦我达到第 17 个,它就会抛出段错误!
这是抛出它的代码,完全没问题!
for (int i = 0; i < Nx*Ny; i++) {
array[i] = 0;
}
我真的不知道为什么,我想到了 运行 out of heap,但是因为我有 4GB 的 RAM 这应该是不可能的! 我在 Windows 10!
上使用 MSVS15 和 运行 程序知道为什么会这样吗? 确切错误:
Exception thrown at 0x00298389 in ecostress.exe: 0xC0000005: Access violation writing location 0x01D2B000. If there is a handler for this exception, the program may be safely continued.
简单的错字:
double* array = new double(Nx*Ny); // creates a single, initialized double
double* array = new double[Nx*Ny]; // creates an array of doubles
@Hurkyl 回答正确。
我只是想补充一点,如果是在 C++ 上,那么最好使用向量:
vector<int> array(Nx*Ny);
要直接访问指针,您可以使用 &array[0]
,虽然通常没有理由这样做,但您仍然可以这样做 array[0] = 0
。
vector
和 stl 的优点通常是它通过析构函数自动释放内存。