rand_s
The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.
The latest version of this topic can be found at rand_s.
Generates a pseudorandom number. A version of rand with security enhancements as described in Security Features in the CRT.
Syntax
errno_t rand_s( unsigned int* randomValue);
Return Value
Zero if successful, otherwise, an error code. If the input pointer randomValue
is a null pointer, the function invokes an invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, the function returns EINVAL
and sets errno
to EINVAL
. If the function fails for any other reason, *randomValue
is set to 0.
Remarks
The rand_s
function writes a pseudorandom integer in the range 0 to UINT_MAX
to the input pointer. The rand_s
function uses the operating system to generate cryptographically secure random numbers. It does not use the seed generated by the srand function, nor does it affect the random number sequence used by rand
.
The rand_s
function requires that constant _CRT_RAND_S
be defined prior to the inclusion statement for the function to be declared, as in the following example:
#define _CRT_RAND_S
#include <stdlib.h>
rand_s
depends on the RtlGenRandom API, which is only available in Windows XP and later.
Requirements
Routine | Required header |
---|---|
rand_s |
<stdlib.h> |
For more information, see Compatibility.
Example
// crt_rand_s.c
// This program illustrates how to generate random
// integer or floating point numbers in a specified range.
// Remembering to define _CRT_RAND_S prior
// to inclusion statement.
#define _CRT_RAND_S
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
int main( void )
{
int i;
unsigned int number;
double max = 100.0;
errno_t err;
// Display 10 random integers in the range [ 1,10 ].
for( i = 0; i < 10;i++ )
{
err = rand_s( &number );
if (err != 0)
{
printf_s("The rand_s function failed!\n");
}
printf_s( " %u\n", (unsigned int) ((double)number /
((double) UINT_MAX + 1 ) * 10.0) + 1);
}
printf_s("\n");
// Display 10 random doubles in [0, max).
for (i = 0; i < 10;i++ )
{
err = rand_s( &number );
if (err != 0)
{
printf_s("The rand_s function failed!\n");
}
printf_s( " %g\n", (double) number /
((double) UINT_MAX + 1) * max );
}
}
Sample Output
10
4
5
2
8
2
5
6
1
1
32.6617
29.4471
11.5413
6.41924
20.711
60.2878
61.0094
20.1222
80.9192
65.0712