Mohammad Amin
Mohammad Amin

Reputation: 55

C: "Access Violation" error on runtime

Please look at my code:

adj = (int *)calloc(n * n, sizeof(int));

scanf("%d", &m);

for (i = 0; i < m; i++) {
    scanf("%d %d %d", &x, &y, &w);
    adjSetter(x - 1, y - 1, w);
    adjSetter(y - 1, x - 1, w);
}

This part is in the main function and adjSetter is as below:

void adjSetter(int i, int j, int value) {
    *(adj + (i * n + j) * sizeof(int)) = value;
}

Now the problem is when adjSetter function is called with i more than 2500 then I will get an Access Violation error. What's wrong with my code?

P.S.: n is 10000

Upvotes: 0

Views: 251

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

When i = 2500, n = 10000, j = 0, sizeof(int) = 4, (i * n + j) * sizeof(int) will become 100000000.

*(adj + (i * n + j) * sizeof(int)) is equivalent to adj[(i * n + j) * sizeof(int)], so accessing adj[100000000] will cause out-of-range access, which invokes undefined behavior if only 100000000 elements are allocated via adj = (int *)calloc(n * n, sizeof(int));.

To fix this problem, remove the harmful * sizeof(int) so that it can access the elements of the array properly.

void adjSetter(int i, int j, int value) {
    *(adj + (i * n + j)) = value;
}

Better thing is to use array indexing, which I think is more easy-to-read and write.

void adjSetter(int i, int j, int value) {
    adj[i * n + j] = value;
}

Upvotes: 4

Related Questions