/ dev / urandom为mmap()提供随机地址

时间:2013-06-22 17:39:17

标签: c linux posix

即使我使用/ dev / urandom,我在调用该函数4次后仍然获得相同的地址位置。这是为什么 ?为什么/ dev / urandom提供非常低的数字或非常高的数字?

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;
}

1 个答案:

答案 0 :(得分:2)

因为您将指针的值与其地址混淆。您想使用p,而不是&p。此外,temp char数组是无用的,将它复制到周围都是不正确的。更正后的代码应为:

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);
}