Search code examples
c++randomoverflowsrand

RNG crashing c++ program


I am currently coding a roguelike, and naturally am using a lot of random number generation.

The problem I'm running up on is that if I "overheat" rand(); my program will crash.

If i'm only generating 20 or so ints per frame, it's fine... but when the amount of random numbers goes into the hundreds, the program crashes. The more I'm producing every frame, the sooner it crashes... which leads me to believe there is some pileup going on.

I've done tests, and at 20 rand(); calls per frame, it will run for 24 hours straight at max speed without crashing. Triple that and it doesn't make it ten minutes.

If I put srand(); in the initialization, i can churn out thousands of random numbers before it locks up - but if I put srand(); within the frame itself, i make it about 2-8 frames. If it matters, I'm using time(null) to seed.

the more frequently i call rand(); the sooner it crashes.

Help?


Solution

  • A few comments and ideas on how to narrow down the source of the issue:

    • It almost certainly is not the srand() or rand() functions causing the crash/lock up. Chances are that one, or more, combinations of random numbers is getting your engine into a state where something bad happens.
    • The first step should be to duplicate the issue such that it always happens at the time/place. Instead of using a srand(NULL) try using a constant seed like srand(12345). Depending on what other factors your engine uses (like user input) this may be enough to get it to crash in the same spot each time.
    • If using the debugger is having issues (which is suspect, perhaps a buffer overflow is corrupting the stack) use the tried and true method of outputting messages to a text log file. I would suggest outputting all the random numbers generated and perhaps you may see a pattern on when it crashes (i.e, it crashes whenever a "42" is generated). Another option is to start adding a few log message in various functions (start with high level functions like your game update loop). After a crash check the log and begin adding more log messages until you narrow it down to one line/function. This is not as quick as using the debugger can be but is sometimes a better choice, especially if you don't really know where to start looking.
    • Once you are able to reliably replicate the crash start removing things until the crash point changes or disappears. This may involve #ifdefs, commenting out code, setting application options, or even creating a temporary copy of the project so you can simply delete code, compile, and test. This may be difficult if the project is large/complex.
    • More information on the type of "crash" would be helpful. Usually programs don't just crash generically but have a certain exception occur, lock-up, etc.... Exception details can help you narrow down the source of the issue with some effort.