elaine
elaine

Reputation: 119

/dev/urandom to provide random addresses to mmap()

I keep getting the same address locations after calling the function 4 times even though I am using /dev/urandom. Why is that ? Why is /dev/urandom providing very low numbers or very high ones?

104
0x7fffb128de78
0x7f9e3c565000
4294967192
0x7fffb128de78
0x7f9e3c564000
97
0x7fffb128de78
0x7f9e3c563000
4294967139
0x7fffb128de78
0x7f9e3c562000
void test(void){
    char random[4];
    int filedescriptor = open("/dev/urandom", O_RDONLY);
    read(filedescriptor, random, 4);
    close(filedescriptor);

    unsigned int hintmemoryaddress = (unsigned int)random;
printf("%u\n", hintmemoryaddress);

    char *p = (char *)hintmemoryaddress;
    p += hintmemoryaddress;
printf("%p\n", &p);

    char *x = (char *)mmap((void *)&p, 1000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
printf("%p\n", x);
}

int main(void){
    test();
    test();
    test();
    test();

    return 0;
}

Upvotes: 0

Views: 923

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215517

Because you're confusing the value of a pointer with its address. You want to use p, not &p. Further, the temp char array is useless, and your copying it to around is all incorrect. The corrected code should be:

void test(void){
    void *p;
    int filedescriptor = open("/dev/urandom", O_RDONLY);
    read(filedescriptor, &p, sizeof p);
    close(filedescriptor);

    char *x = (char *)mmap(p, 1000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    printf("%p\n", x);
}

Upvotes: 2

Related Questions