Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

the function getrandom() only returning -1

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<iostream>
#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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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<iostream>
#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;
}

source:
https://man7.org/linux/man-pages/man2/getrandom.2.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading