Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc implementation of rand()

Tags:

gcc

I've tried for hours to find the implementation of rand() function used in gcc... It would be much appreciated if someone could reference me to the file containing it's implementation or website with the implementation.

By the way, which directory (I'm using Ubuntu if that matters) contains the c standard library implementations for the gcc compiler?

like image 717
Sason Avatar asked Oct 14 '10 12:10

Sason


People also ask

What is the MAX value of rand() in C?

The value of this macro is an integer constant representing the largest value the rand function can return. In the GNU C Library, it is 2147483647 , which is the largest signed integer representable in 32 bits. In other libraries, it may be as low as 32767 .

Why is Rand returning same number?

The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.

What is the time complexity of rand function?

It's O(1) complexity, there is no input and it returns one int .


2 Answers

rand consists of a call to a function __random, which mostly just calls another function called __random_r in random_r.c.

Note that the function names above are hyperlinks to the glibc source repository, at version 2.28.

The glibc random library supports two kinds of generator: a simple linear congruential one, and a more sophisticated linear feedback shift register one. It is possible to construct instances of either, but the default global generator, used when you call rand, uses the linear feedback shift register generator (see the definition of unsafe_state.rand_type).

like image 57
Tom Anderson Avatar answered Sep 21 '22 22:09

Tom Anderson


You will find C library implementation used by GCC in the GNU GLIBC project.

You can download it sources and you should find rand() implementation. Sources with function definitions are usually not installed on a Linux distribution. Only the header files which I guess you already know are usually stored in /usr/include directory.

If you are familiar with GIT source code management, you can do:

$ git clone git://sourceware.org/git/glibc.git

To get GLIBC source code.

like image 36
Pablo Santa Cruz Avatar answered Sep 24 '22 22:09

Pablo Santa Cruz