How to check if a memory address is writable or not at runtime?

How to check if a memory address is writable or not at runtime?

For example, I want to implement is_writable_address in the 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;
}

      

+3


source to share


2 answers


I generally agree, which suggests that this is a bad idea.

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

      

+5


source


It may be technically possible, but there is no portable way to do it, and it will never be necessary for it. If you manage to lose information about whether a pointer is writable or not, there is even more important information that you do not know either, for example, what it points to, and whether your write or not.



0


source







All Articles