jeudi 30 avril 2015

segmentation fault while generating a number of random numbers using rand() in C

I am writing a program where I need to set a number of elements (specified by the blanks variable) of a 2D array (board) to be 0.(array size is 9x9) These locations has to be picked up in random and once I use the following code segment to do it, the program ends up in a segmentation fault in some instances and does not set the required number of positions to 0.

i = rand() % 10;
j = rand() % 10;

if (board[i][j]){
    board[i][j] = 0;
    blanks--;
}

I have been looking up on this issue bit and came to know that rand() is not thread safe. Is it the reason for the segmentation fault I am getting, or is it something else?

Further, is there a workaround for this? (For me to get a set of random numbers without this segmentation fault)




Aucun commentaire:

Enregistrer un commentaire