-2

I have to select random number between 0 and 3. I have to call this function several times. In the beginning it's always working but after some time the error message Tread 1: EXC_BAD_ACCESS(code =2, address 0x7fff5f3ffff8 appears.

Here is my code. m_p[multiproject][project] is equal to 4;

int selecteer_random_resource(int multiproject, int project)
{   int k=0;
    k=rand()%m_p[multiproject][project];
    return k;
}

I really don't understand why it's working in the beginning and after some time the error appears.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
  • Really depends on what `m_p`, `multiproject`, and `project` are don't you think? Try editing the code into a short complete example. – Retired Ninja Mar 29 '15 at 10:56
  • Look at the answer here http://stackoverflow.com/questions/16363513/cocos2d-x-exc-bad-access-code-2-address-0x0-when-initializing-a-cctmxtiledm and try your debugger –  Mar 29 '15 at 11:02

1 Answers1

0

rand() is not thread safe, and it says so in the documentation. Citing https://stackoverflow.com/a/6161352/4433386:

That said, the documentation states:

The function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call. This might just be the seed value to be used by the next call, or it might be something more elaborate. In order to get reproducible behaviour in a threaded application, this state must be made explicit. The function rand_r() is supplied with a pointer to an unsigned int, to be used as state. This is a very small amount of state, so this function will be a weak pseudo-random generator. Try drand48_r(3) instead.

The emphasized part of the above is probably the reason why all your threads get the same number.

You should, especially in the year 2015, use a thread safe random number generator. Boost/C++11 has the <random> standard library, containing awesome methods to thread-safely generate random numbers.

If you can't use boost or C++11, you can also try drand, e.g. drand48_r.

Community
  • 1
  • 1
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94