How can I check whether a memory address is writable or not at runtime?

c, operating-system, unix

Solution

I generally concur with those suggesting that this is a bad idea.

That said, and given that the question has the UNIX tag, the classic way to do this on UNIX-like operating systems is to use a `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;
}

Problem

How can I check whether a memory address is writable or not at runtime? For example, I want to implement is_writable_address in following code. Is it possible? ``` #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; } ```

Original source

Related problems