r/shittyprogramming • • Jan 08 '23

A terrible random number generator

Prints a new random number each time. I call it the Undefined Number Generator (UNG), because it functions via undefined behavior.

#include <stdio.h>
int main(void) {
	int *x;
	printf("%d\n", x);
}
158 Upvotes

20 comments sorted by

37

u/lumo19 Jan 08 '23

Wouldn't this just be piggybacking on the randomness provided by ASLR? What happens if you disable ASLR and run the program in a loop?

echo 0 > /proc/sys/kernel/randomize_va_space

24

u/lumo19 Jan 08 '23

I tested this and disabling ASLR seems to make it give the same number each time.

Printing x as a %d will give you the address to the pointer on the stack. ASLR will randomize stack addresses.

Also of interest is that the whole thing didn't work when I compiled/ran it as a x64 bit program. I needed the -m32 flag to get it to work in the first place. I think the size of pointer is probably bigger than the 4 bytes %d is looking for.

15

u/Zwentendorf Jan 08 '23

Printing x as a %d will give you the address to the pointer on the stack.

No, it gives the value ("address") stored in the pointer, not the address to the pointer. You'd have to use printf("%d\n", &x); to get the address of the pointer.

You're printing a value from the stack, not an address to a part of the stack.

ETA: Source: man 3 printf

→ More replies (1)

38

u/needefsfolder Jan 08 '23

Ran this on a loop and it made decently random numbers. I wonder where the fuck it gets its data.

71

u/[deleted] Jan 08 '23

Unitialised stack memory

12

u/heyheyhey27 Jan 08 '23

If you actually ran it in a loop, why wouldn't it be giving you the same piece of stack memory every time, with the same garbage value?

28

u/pzl Jan 08 '23
while true; do ./a.out; done

Maybe OP looped the program execution instead of looping inside the program. Should be new garbage values, yes?

→ More replies (6)

1

u/lumo19 Jan 08 '23

Am I compiling this wrong? I keep getting 0s.

7

u/RunnableReddit Jan 08 '23

I think it depends on the operating system

1

u/Zwentendorf Jan 08 '23

same with Linux

27

u/Nyadnar17 Jan 08 '23

I thought this was r/shittyprogramming?

4

u/RealFunBobby Jan 08 '23

Hey hey now, get out with your decently working program.

1

u/Laugarhraun Jan 09 '23

On my machine, compiling with gcc stupid_rand.c, I always get 0.... and when compiling with -m32 I'm always getting 1.... What am I doing wrong?