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