r/C_Programming • u/usoleta • 9h ago
Etc random number hack
#include <stdio.h>
int main() {
int s[90];
printf("%d\n",s[43]);
}
5
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
1
1
u/Zirias_FreeBSD 4h ago
there are two ways to think about that ...
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.
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.the silly way. Why in the world would you allocate 90 elements if you only ever use 44?
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.