尝试填充动态数组时出现访问冲突(大量项目)
Access violation on try to fill dynamic array (large number of items)
我有以下 C 代码:
int dimension;
double *AtS;
...
AtS=(double*)malloc(sizeof(double)*dimension);
for (i=0; i<dimension; i++)
{
AtS[i]=0.0;
}
虽然 dimension
约为 6-8 百万,但它工作正常,但当它约为 3 亿时,它会因访问冲突而失败。调试中的以下消息:
Unhandled exception at 0x012f1077 in mathpro.exe: 0xC0000005: Access violation writing location 0x00000000.
如果我使用 memset()
而不是循环,情况相同。
有什么办法可以解决这个问题吗?
“访问冲突写入位置0x00000000”由手册解释
http://man7.org/linux/man-pages/man3/malloc.3.html#RETURN_VALUE
On error, these functions return NULL.
或者如果你喜欢 http://www.cplusplus.com/reference/cstdlib/malloc/.
Return Value
On success, a pointer to the memory block allocated by
the function. The type of this pointer is always void*, which can be
cast to the desired type of data pointer in order to be
dereferenceable. If the function failed to allocate the requested
block of memory, a null pointer is returned.
您遇到了一个错误。很可能内存不足。
如果您在将值 sizeof(double)*dimension
传递给 malloc 之前对其进行检查,您会发现它确实是一个很大的数字。
正如 Captain Giraffe in the 先生已经解释的那样,您遇到这个问题是因为通过 malloc()
的内存分配失败了(很可能 非常大 分配请求)并且在使用 returned 指针之前没有检查 malloc()
是否成功。
万一失败。 malloc()
将 return NULL
并且在没有检查的情况下,您将取消引用 NULL
指针,该指针又会调用 undefined behaviour.
除此之外,我还要补充三点,例如
我有以下 C 代码:
int dimension;
double *AtS;
...
AtS=(double*)malloc(sizeof(double)*dimension);
for (i=0; i<dimension; i++)
{
AtS[i]=0.0;
}
虽然 dimension
约为 6-8 百万,但它工作正常,但当它约为 3 亿时,它会因访问冲突而失败。调试中的以下消息:
Unhandled exception at 0x012f1077 in mathpro.exe: 0xC0000005: Access violation writing location 0x00000000.
如果我使用 memset()
而不是循环,情况相同。
有什么办法可以解决这个问题吗?
“访问冲突写入位置0x00000000”由手册解释
http://man7.org/linux/man-pages/man3/malloc.3.html#RETURN_VALUE
On error, these functions return NULL.
或者如果你喜欢 http://www.cplusplus.com/reference/cstdlib/malloc/.
Return Value
On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a null pointer is returned.
您遇到了一个错误。很可能内存不足。
如果您在将值 sizeof(double)*dimension
传递给 malloc 之前对其进行检查,您会发现它确实是一个很大的数字。
正如 Captain Giraffe in the malloc()
的内存分配失败了(很可能 非常大 分配请求)并且在使用 returned 指针之前没有检查 malloc()
是否成功。
万一失败。 malloc()
将 return NULL
并且在没有检查的情况下,您将取消引用 NULL
指针,该指针又会调用 undefined behaviour.
除此之外,我还要补充三点,例如