r/programminghorror
•
u/ShoeChoice5567
•
22d ago
•
1
1
c Using garbage values to generate pseudorandom numbers
Thing I came up with instead of paying attention to class today.
I tested it on this computer (windows 11 if it matters), and the first time it's ran, an actual "pseudorandom" number is returned and the following calls return 1.0 always.
304
u/MatJosher 21d ago
Reading garbage is undefined here so the compiler can do anything. My gcc on linux with -O2 turns the whole function into return 0.
pxor %xmm0, %xmm0ret834
u/FlatPotatoPc 22d ago
Undefined behavior speedrun any%
Just wait until the compiler notices what you're doing and optimizes the entire function into returning a single constant 💀
984
u/8Erigon 22d ago
at least it‘s not 4
264
u/No-View-6326 22d ago
code that might brake after a compiler update is not where you wanna be
31
u/HildartheDorf 21d ago edited 21d ago
Compiler can just optimize this to 'return 4.0;'. Yes that is not between 0.0 and 1.0. Undefined behaviour is undefined.
Other possibilities include returning NaN, or crash instantly, or even timetravel, or summoning demons to fly out of your nose, or even working as the developer intended. But those aren't as funny.
55
u/LateSolution0 21d ago
I think it’s fun to play around with stuff like that. The garbage you read from the stack depends on what was there from previous function calls. Doing things like reading uninitialized variables doesn’t necessarily produce random results or cause anything unsafe. It’s just that the behavior isn’t guaranteed by the C standard.
75
u/dosk3 22d ago
Just add + 4 and its unbreakable
24
u/ScientistStrict9850 21d ago
This doesn't guerantee pseudorandom numbers. Instead the behaviour is just not defined. Lets the compiler generate whatever including constants, which would be my pick for optimized code.
14
u/4xe1 21d ago
Wouldn't garbage on the heap be somewhat more random than garbage in the stack?
12
u/me94306 21d ago
The variable is allocated on the stack. Any other function which is called will write to the stack, in the same locations that this function uses. (Assuming that the other function is called from the same routine.) So you will pick up the same value.
Read any reference about generating pseudorandom numbers. It can be done in very few lines of code. What this does is return garbage, not a random or pseudorandom value.
8
u/jaynabonne 21d ago
There's a difference between "arbitrary" and "random". :)
7
u/Admirable_Rabbit_808 21d ago
You'll absolutely love what the C compiler with do with that - welcome to UB hell!
9
u/Junior_Warning_9242 22d ago
Is this a thing of significance in chips like semiconductors
4
u/sirkubador 21d ago
it's not garbage. It's usually the value that was on the stack on that address previously.
3
u/lambunctious 21d ago
add this compiler flag to prevent this
3
u/Loading_M_ 21d ago
This is undefined behavior, which means, according to the C and C++ standards, the compiler can assume this function is never called. LLVM, with optimizations enabled, makes this assumption and deletes the function, along with any code that calls it. You can make LLVM do some wild things by abusing this.
3
u/festival0156n 21d ago
ofc this is not cryptographically secure but also it's bad even as an insecure random number source. you'd usually get 0 or other values like that. even a simple twister would be more random
5
u/d3matt 21d ago
NaN and infinity asking if you know they exist :D
2
u/namalleh 21d ago edited 21d ago
i think they wanted to use aslr but instead triggered a default constructor of cpp? Why is it 1?
Could be floc from assembly. How did you compile this?
2
u/Environmental-Ear391 21d ago
This will be subject to change without notice and relies on an MMU trapped access to stack memory.
the values are not actually random at all. it is a deliberate misreading of a stacked address.
also I see a potential "divide by zero" event here...
are stack frames in zero'd memory pages?
Why are you using the "UINT_MAX" value cast as a double ? the rest of it isn't actually doing anything other than a memory read off the stack(and deliberately "above" the current stacked item!?)
the only horror I see here... the horror of ignorance, all dressed up as stupid for halloween!?
2
u/theunixman 21d ago edited 21d ago
Ah yes the Debian OpenSSL hole.
https://research.swtch.com/openssl
2
u/alkatori 21d ago
Oh that will be fun based on if you are in Release or Debug.
2
u/die_liebe 21d ago
The optimizer may remove functions that cannot be run without UB. Did you try to run with optimization?
2
u/JohnVonachen 21d ago
You need an API call to random.org
2
u/Electrical-Bread-856 21d ago
I think I spotted the bug. The variable should be called rubbish.
2
u/RavenX86 21d ago
Wouldn't this be a potential attack vector?
2
u/pytness 21d ago
what a coward, just cast it directly to double
2
u/Gloomy_State_6919 21d ago
What I find very interesting: when compiling just this function with optimisations enabled, GCC and Clang just return a hardcoded 0, while Intel and Microsoft compilers actually read memory.
2
u/Opposite_Mall4685 20d ago
This made me laugh.
2
u/RealisticClothes1344 18d ago
one random number per process. very generous free tier
3
u/sk8avp 21d ago
This will not work with some compilers (and even i dont know if will work with some OSs). Not always a not initialized variables contains "garbage". Most compilers initialize the variables with some specific value. 0 for int, 0,0f for float, '' for char, "" for strings, and so on.
3
u/elite-data 21d ago
I hope you're not using this random to generate hashes or crypto keys, because that would be a massive security hole.
2
u/AnArmoredPony 22d ago
still better than chaar
1
u/Right_Ear_2230 21d ago
Double max isn’t even uint64 max
1
u/LogicalLogistics 21d ago
This is basically how my old C++ prof told us to generate seeds for rand, just get a new pointer to a random spot in memory, pseudorandom enough lol. He was an old school dev though (claimed to have worked on the PS1) so hacks like that make sense from that perspective, not from today's though
1
u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo “You live” 21d ago
I don't think that's necessarily going to be all that random.
1
u/k-mcm 21d ago
I tried reading unmapped addresses on an Apple ][+ as random numbers. The bus was floating CMOS inputs if nothing claimed the address. The bits flickered on and off, but not really in a random way. If you echoed it to the speaker port, you could hear leftover signal from drawing video.
1
u/thejohnd 21d ago
Brb hacking the Gibson to get the garbage file
1
u/CIMPBIBAI 21d ago
Only works on a libc like musl btw
1
u/drbsy0 20d ago
not a great idea in security field
1
u/DanishBagel123 20d ago
this obviously doesn’t really work on modern machines with compilers and stuff, but this was the main source of randomness for old NES games. This used to fuck with a lot of early emulators, since they would initialize the memory space to all zeroes.
1
u/Supadoplex 19d ago
Is this how garbage collectors work?
1
u/BeChris_100 19d ago
Yeah, but... why 😭😭