如何在运行时检查内存地址是否可写?

Tak*_*ato 4 c unix operating-system

如何在运行时检查内存地址是否可写?

例如,我想在以下代码中实现is_writable_address.可能吗?

#include <stdio.h>

int is_writable_address(void *p) {
    // TODO
}

void func(char *s) {
    if (is_writable_address(s)) {
        *s = 'x';
    }
}

int main() {
    char *s1 = "foo";
    char s2[] = "bar";

    func(s1);
    func(s2);
    printf("%s, %s\n", s1, s2);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

caf*_*caf 5

我通常同意那些暗示这是一个坏主意的人.

也就是说,鉴于问题有UNIX标签,在类UNIX操作系统上执行此操作的经典方法是使用read()from /dev/zero:

#include <fcntl.h>
#include <unistd.h>

int is_writeable(void *p)
{
    int fd = open("/dev/zero", O_RDONLY);
    int writeable;

    if (fd < 0)
        return -1; /* Should not happen */

    writeable = read(fd, p, 1) == 1;
    close(fd);

    return writeable;
}
Run Code Online (Sandbox Code Playgroud)