0

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

  • [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Jun 17 '16 at 14:13
  • 1
    You have some undeclared variables. Please post a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – MikeCAT Jun 17 '16 at 14:13
  • 2
    `* sizeof(int)` Hmmm, this smells. Learn about pointer aritimetics. – MikeCAT Jun 17 '16 at 14:13
  • Not testing the return value from scanf is always asking for surprises. – Jens Jun 17 '16 at 14:30

1 Answers1

4

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;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70