RayB
RayB

Reputation: 2356

C++ Access Violation Error when setting value

can someone explain to me why this code get's an access violation error when the last line runs but not when h_A[0] is set to 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;

The error is:

Unhandled exception at 0x01079554 in Test.exe: 0xC0000005: Access violation writing location 0x00000000.

Edit:

Here is the solution thanks to @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
}

Upvotes: 0

Views: 138

Answers (1)

owacoder
owacoder

Reputation: 4873

The second allocation failed, while the first did not. (i.e. malloc returned NULL, out of memory) You should put error checking for an out of memory condition in your code.

Upvotes: 5

Related Questions