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;
}
Each address identifies a single byte (eight bits) of storage.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With