• Uncategorized

About c++ : the-function-getrandom-only-returning–1-closed

Question Detail

I am attempting to get random numbers out of the getrandom() function however attempting to use it only returns -1 the code i am using below:

#include <sys/random.h>
int main(){
    void* d = NULL;
    ssize_t size = 10;
    ssize_t p = getrandom(d, size, GRND_RANDOM);
    std::cout << p << std::endl;

Question Answer

getrandom returns the number of bytes written. The first argument is the pointer to a byte buffer (to be filled with random bytes), the second argument is the number of random bytes that you want to be written to the buffer.

Your return value (p) being -1 means that there was an error when writing the random bytes to the buffer. This error in your case is because you are passing in NULL as the pointer to the buffer to be filled.

Try this instead:

#include <sys/random.h>
int main(){
  unsigned char random_bytes[2]; // buffer where getrandom will store the random bytes
  ssize_t size = 2;
  ssize_t p = getrandom((void*) &random_bytes[0], size, GRND_RANDOM);
  std::cout << "First random value: " << random_bytes[0] << std::endl;
  std::cout << "Second random value: " << random_bytes[1] << std::endl;


You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.