Skip to content
Advertisement

Why does the Code run on Linux but not on Windows?

Well, I wrote a little Program that should generate random values, but no value should be in the output file twice. On Linux it’s running perfectly, but on Windows it just runs infinity long on the 32768th value. That means, that cmd is open but nothing really happens from that point.

I already did debug it 30 times by now but it never had any problem (it was hell do debug it) I wrote it new, recompiled it, even changed values under it was running through the debugger

Here is the Code:

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

int intlen(int[]);

int main(int argc, char *argv[]) {
    FILE *fp;
    int percent = 0;
    int Ergebnis = 0, length = 0, lenNow = 0;
    bool proof = true;
    srand(time(NULL));
    fp = fopen("ranGen.txt", "w");
    length = atoi(argv[1]);
    int Lookup[length];
    for (int x = 0; x < length; x++){
        Lookup[x] = 0;
    }
    for (int i = 0; i < length; i++) {
        do {
            proof = true;
            Ergebnis = rand() % (2147483646 - 1 + 1) + 1;

            for (int j = 0; j < length && Lookup[j] != 0 && proof != false; j++) {
                if (Ergebnis == Lookup[j]) {
                    proof = false;
                }
            }
        }while(proof == false);
        Lookup[lenNow] = Ergebnis;
        lenNow++;
        fprintf(fp,"%i ",Ergebnis);
    }
    return 0;
}

posted everything, but the output because I don’t really know where the problem is and I think you will need the most of it reproduce my problem. if you compiled it, run it through cmd with something like 50000, so that it is higher than 32768.

(like this: example.exe 50000)

Expected was, that it will create a File named RanGen.txt with 200000 random values (200000 was my test value)

But the output was 32767 Values in the text Document and then the program just did nothing more.

Solution: used rand() % 214748346; instead of rand() % (214748346 - 1 + 1) + 1;

Advertisement

Answer

Looks like rand() is only 16 bits in that library. Make it 32 bits by calling it twice:

int rand32() {
    return rand() ^ (rand() << 16);
}

Also, consider eliminating the inner duplicate-search loop by using Bob Floyd’s algorithm: https://blog.acolyer.org/2018/01/30/a-sample-of-brilliance/

Advertisement