Bewerken

Delen via


rand_s

Generates a pseudorandom number. This function is a more secure version of the function rand, with security enhancements as described in Security features in the CRT.

Syntax

errno_t rand_s(unsigned int* randomValue);

Parameters

randomValue
A pointer to an integer to hold the generated value.

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 doesn't use the seed generated by the srand function, nor does it affect the random number sequence used by rand.

The _CRT_RAND_S constant must be defined before the stdlib.h header for the rand_s function is included, as shown in the following example:

By default, this function's global state is scoped to the application. To change this behavior, see Global state in the CRT.

#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.

// Remember to define _CRT_RAND_S before you include
// stdlib.h.
#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

See also

Math and floating-point support
rand
srand