0
votes

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
}
1
Because you didn't check whether malloc succeeded. - emlai
Any particular reason you feel the need to attempt to allocate about 1GB of memory at a time to then set a value that would fit in char or is this completely out of context? As mentioned your second malloc is likely failing ... if I had to guess it's because you're consuming more than the addressable space for a 32-bit process. - AJG85
@AJG85 it's for a class. We're supposed to use large numbers to test the difference between CUDA and CPU computations. - RayB

1 Answers

5
votes

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.