Reputation: 25
In my main funtion, the function fragment below is looped to keep generating two numbers between 0 and 4. The first time it goes through the loop it works fine, but the second time it gets core dumped. I'm not sure if it's because of a bug somewhere else or if I just didn't use the rand and srand properly. Very new to c language here.
void generate_player2_move(char board[][SIZE], int row, int col) {
//segmentation fault (core dumped) somewhere around here.
int randrow, randcol;
srand((unsigned) randrow);
srand((unsigned) randcol);
row = rand() % 4;
col = rand() % 4;
}
Upvotes: 0
Views: 165
Reputation: 223872
The code you've shown doesn't do anything that could cause a core dump, so that's probably in code you haven't shown. You are however using srand
incorrectly.
Random numbers returned by the rand
function are actually a sequence of numbers that are passed through a function, with the last output being the new input. This function needs to be seeded before it runs for the first time, and that's what the srand
function does.
You should be calling srand
only once at the beginning of your program. After that, just call rand
whenever you need a new random number.
Upvotes: 3