如何在运行时检查内存地址是否可写? [英] How can I check whether a memory address is writable or not at runtime?

查看:9
本文介绍了如何在运行时检查内存地址是否可写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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
", s1, s2);
    return 0;
}

推荐答案

我一般同意那些认为这是一个坏主意的人.

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

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

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;
}

这篇关于如何在运行时检查内存地址是否可写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆