Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 336
Takayuki Sato Avatar asked Jan 21 '13 06:01

Takayuki Sato


People also ask

Are memory addresses in bytes?

Each address identifies a single byte (eight bits) of storage.

How does memory address work in c++?

When a variable is created in C++, a memory address is assigned to the variable. And when we assign a value to the variable, it is stored in this memory address.

Where is memory address stored in C program?

When a variable is created in C, a memory address is assigned to the variable. The memory address is the location of where the variable is stored on the computer. When we assign a value to the variable, it is stored in this memory address.


1 Answers

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;
}
like image 132
caf Avatar answered Oct 07 '22 20:10

caf