0

I have a simple test program in C to scramble an array of values on the heap. Sidenote: I know the random logic here has a flaw that will not allow the "displaced" value to exceed RAND_MAX, but that is not the point of this post.

The point is that when I run the code with N = 10000, every once in a while it will crash with very little information (screenshots posted below). I'm using MinGW compiler. I can't seem to reproduce the crash for lower or higher N values (1000 or 100000 for example).

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

const int N = 10000;

int main() {
    int i, rand1, rand2, temp, *values;

    /* allocate values on heap and initialize */
    values = malloc(N * sizeof(int));
    for (i = 0; i < N; i++) {
        values[i] = i + 1;
    }

    /* scramble */
    srand(time(NULL));
    for (i = 0; i < N/10; i++) {
        rand1 = (int)(N*((double)rand()/(double)RAND_MAX));
        rand2 = (int)(N*((double)rand()/(double)RAND_MAX));
        temp = values[rand1];
        values[rand1] = values[rand2];
        values[rand2] = temp;
    }


    int displaced = 0;
    for (i = 0; i < N; i++) {
        if (values[i] != (i+1)) {
            displaced++;
        }
    }
    printf("%d numbers out of order\n", displaced);

    free(values);
    return 0;
}

enter image description here

The111
  • 5,757
  • 4
  • 39
  • 55

1 Answers1

3

it may be because rand() generates a random number from 0 to RAND_MAX inclusive so (int)(N*((double)rand()/(double)RAND_MAX)) can be N, which exceeds the array boundary. however, i don't see why that would vary with array size (it does explain why it only crashes sometimes, though).

try /(1+(double)RAND_MAX) (note that addition is to the double, to avoid overflow, depending on the value of RAND_MAX) (although i'm not convinced that will always work, depending on the types involved. it would be safer to test for N and try again).

also, learn to use a tool from Is there a good Valgrind substitute for Windows? - they make this kind of thing easy to fix (they tell you exactly what went wrong when you run your program).

Community
  • 1
  • 1
andrew cooke
  • 45,717
  • 10
  • 93
  • 143