Geeklat
Geeklat

Reputation: 167

C++ Random Number Causing Crash when printing out value only. Very strange

I need a value between 0.0 and 1.0. So I seed the random number generator using time. Then I get a value between 0 and 10 using the rand function. After that I take that value and divide it by 10 to get my decimal value. My issues is that the program will randomly crash when I try and print out the value generated by (dRandNum % 10). Also of note is that it is not crashing in the middle of the for loop. It's always right at the beginning on the first attempt to print out. I'm honestly thinking that there's just something really strange with the compiler and was wondering if anyone could direct me otherwise.

double dRandNum = 0;
int tempRand = 0;

/* initialize random seed: */
srand ( (unsigned)time(0) );


for(int i = 0; i < 40; i++)
{
      tempRand = rand();
      cout << "tempRand= " << tempRand << endl;
      dRandNum = tempRand % 10;// + 1;

      // Crashes here for some reason.  If I don't try and print the value it's fine
      cout << "Random Num Before " << i << ": " << dRandNum << endl;

      dRandNum = dRandNum / 10;
      cout << "Random Num After " << i << ": " << dRandNum << endl;
      weights[i] = dRandNum;
} 

Upvotes: 0

Views: 1166

Answers (2)

Hans Passant
Hans Passant

Reputation: 941327

For the sake of the program one can assume the function is wholly independent

That's a big mistake, it never is. This has heap corruption written all over it. Which rarely causes a crash at the line of the code that corrupts the heap. Always later, sometimes much later.

Upvotes: 2

John R. Strohm
John R. Strohm

Reputation: 7667

OK, I'm going to take a random stab here and ask you to show us the declaration of the weights[] array.

And I'll even wager the traditional virtual jelly doughnut that weights[] is not declared to hold 40 elements.

Upvotes: 3

Related Questions