我编写的代码在 OS X 中没有任何问题,但在 VS 2013 社区上运行时出现以下错误。
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
}
}
关于c - malloc() 并分配 : C code in run well in OS X; not in Win 8. 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36962707/