尝试填充动态数组时出现访问冲突(大量项目)

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.

除此之外,我还要补充三点,例如

  1. do not castmalloc()和家人C的return值。

  2. 您无需使用 loop 将(正确)分配的内存初始化为 0。相反,要以有效的方式完成此操作,请使用

    • 您可以使用 calloc(),return 内存设置为零。
    • 您可以使用 malloc() 然后 memset() 将分配的内存设置为 memset().
    • 提供的特定值
  3. 在表达式中使用 malloc() 稳健 方法是将表达式写为

    AtS=malloc(dimension * sizeof*AtS);   //sizeof is an operator
    

    独立于AtS类型。稍后,如果更改 AtS 的类型,则根本不需要修改此表达式。