malloc()和assign:C代码在OSX中运行良好;而不是在Win 8.1中



我编写的代码在OSX中运行时没有任何问题,但在VS2013社区上运行时出现了以下错误。

Unhandled exception at 0x001A3D22 in Myproject.exe: 0xC0000005:
Access violation writing location 0x00000000.

这是有问题的代码。原始代码还有几行,但下面的代码本身会产生相同的错误。

#include <stdio.h>
int main(void){
    int **p;
    p = (int **)malloc(sizeof(int *) * 5000);
    for (int i = 0; i < 5000; i++)
        p[i] = (int *)malloc(sizeof(int) * 5000 * 25);
    for (int i = 0; i < 5000 * 25; i++) p[0][i] = 0;
    for (int i = 1; i < 5000; i++) p[i][0] = 0;      //<- error on this line
    printf("donw!n");
    system("pause");
    return 0;
}

这是发生错误时的状态。i和p的颜色为红色。

    name        value                         type
    i           4118                          int
    p           0x00758fe8 {0x0075de48 {0}}   int * *
    p[0]        0x0075de48 {0}                int *
    p[0][i]     0                             int
    p[i]        0x00000000 {???}              int *

有人能告诉我OSX和Windows之间的区别是什么吗?在OSX中,我使用gcc编译了代码。

p[i]NULL时,很可能是malloc未能分配所需内存的结果。添加检测。

p = (int **)malloc(sizeof(int *) * 5000);
if ( p == NULL )
{
   // Deal with error.
}
for (int i = 0; i < 5000; i++)
{
   p[i] = (int *)malloc(sizeof(int) * 5000 * 25);
   if ( p[i] == NULL )
   {
      // Deal with error
   }
}

相关内容

最新更新