设置值时出现C++访问冲突错误

Ray*_*ayB 0 c++ malloc access-violation

可以有人向我解释为什么这个代码在最后一行运行时会出现访问冲突错误,但是当h_A [0]设置为100时却没有?

int nx = 16384;
int ny = 16384;
int nxy = nx*ny;
int nBytes = nxy * sizeof(int);

int *h_A;
h_A = (int *) malloc(nBytes);
h_A[0] = 100;

int *h_B;
h_B = (int *) malloc(nBytes);
h_B[0] = 100;
Run Code Online (Sandbox Code Playgroud)

错误是:

Test.exe中0x01079554处的未处理异常:0xC0000005:访问冲突写入位置0x00000000.

编辑:

这是@owacoder 的解决方案

int nx = 1238;//8;
int ny = 16384;//6;
int nxy = nx*ny;
int nBytes = nxy * sizeof(int);


int *h_A;
if ((h_A = (int *) malloc(nBytes)) == NULL){
    printf("Malloc failed...\n");
    return 0;
} else {
    initialInt (h_A, nxy); // Fills matrix with numbers
}


int *h_B;
if ((h_B = (int *) malloc(nBytes)) == NULL){
    printf("Malloc failed...\n");
    return 0;
} else {
    initialInt (h_B, nxy); // Fills matrix with numbers
}
Run Code Online (Sandbox Code Playgroud)

owa*_*der 5

第二次分配失败,而第一次没有.(即malloc返回NULL,内存不足)您应该对代码中的内存不足情况进行错误检查.