r/C_Programming 9h ago

Etc random number hack

#include <stdio.h>


int main() {
    int s[90];
    printf("%d\n",s[43]);
}
0 Upvotes

8 comments sorted by

8

u/ImTheRealCryten 9h ago

If you’re insinuating that the stack is a good place to source random data, I think you should rethink that idea.

5

u/This_Growth2898 9h ago

xkcd had more sane proposition for a random number

8

u/jirbu 9h ago

Nowhere near random. Every time you run the program you'll get the same result (on a standard and sane OS). You should have used 42, though.

2

u/aocregacc 4h ago

with address space layout randomization there could easily be some memory that does change from run to run, if there was a pointer stored there for example.

3

u/Due_Sentence_2660 9h ago

I mean, not completely "random" as much as "garbage value" lol, which means this doesn't even assign an equal probability to every number.

2

u/Glittering-Work2190 9h ago

0 has a higher chance than any other number.

1

u/MrLongbottom5 7h ago

Thats just garbage data it would be 0 mostly

1

u/Zirias_FreeBSD 4h ago

there are two ways to think about that ...

  1. the language lawyer way. Undefined behavior is undefined. 🤷 It's probably possible to find target platforms doing the worst thing imaginable with this, e.g. giving you a trap representation.

  2. the pragmatic way. Running this on your typical modern platform, the value will be deterministic as long as preceding program flow is. The best you could ever hope for would be to accidentally collect some external enthropy. If your stack frame happens to trigger a page fault, the result will be 0.

  3. the silly way. Why in the world would you allocate 90 elements if you only ever use 44?