#Random number generator using arrays

5 messages · Page 1 of 1 (latest)

weak phoenix
#

I tried to make a random number generator using arrays and then put it within a range and prevent it from being negative by squaring it but the output still sometimes prints negative numbers. Idk what I'm missing.

#include <stdio.h>

int main()
{
int array[1];
int i = 0;
int number = array[i];

for(i=10; i <= 20; i++){
number = array[i];
printf("%d, ", (number * number) % 21);
}
return 0;
}

output example:

7, 0, 1, 15, 9, -1, 9, 12, 1, 6, 9,

obsidian sageBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

earnest skiff
#

First of all: You're accessing memory that you never allocated, this is UB to begin with and can easily lead to SEGFaults and at best is "just" a major security vulnerability.

Next of all, this isn't a random number generator, it just grabs the values that are still in memory, which aren't random values, just unknown ones, which yet again can (and in fact did) lead to security issues. Here's a Reddit post that somewhat discusses this: https://www.reddit.com/r/C_Programming/comments/39hi2u/does_anyone_ever_use_uninitialized_memory_as_a/

Why does it produce negative numbers? Integer overflows.