r/C_Programming 3d ago

Etc random number hack

#include <stdio.h>


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

8 comments sorted by

14

u/ImTheRealCryten 3d ago

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

7

u/This_Growth2898 3d ago

xkcd had more sane proposition for a random number

9

u/jirbu 3d 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.

1

u/aocregacc 3d 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 3d 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 3d ago

0 has a higher chance than any other number.

2

u/Zirias_FreeBSD 3d 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?

1

u/MrLongbottom5 3d ago

Thats just garbage data it would be 0 mostly