dimanche 10 mars 2019

C rand() function breaking program

I'm developing a program in C, and I am making use of the rand() function. For some reason, however, the function seems to be breaking my code, and I cannot figure out why. If I get rid of the random number generator, the code works flawlessly, however as soon as I add the random generator, it breaks once more. The weird part is, the random number being generated is only being used in one conditional, nowhere else. Here is my code:

void random1Byte(){
    int mallocCounter = 0;
    char* pointersArr[50];
    int arrIndex = 0;
    int random;
    srand(time(NULL));
    while (mallocCounter < 50){
        //even represents malloc
        random = rand() % 10;
        if (random % 2 == 0){
            mallocCounter++;
            pointersArr[arrIndex++] = (char*) malloc(1);
        }
    }
}

If I take

random = rand() % 10;

and I change it to

random = 6; //Random number, even so that it doesn't cause an infinite loop

The code executes flawlessly. The code makes it past

mallocCounter++;

but stops there.




Aucun commentaire:

Enregistrer un commentaire