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

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

问题描述

我如何检查内存地址是否可写,或者根本不运行?

例如,我要实现以下code is_writable_address。这可能吗?

 的#include<&stdio.h中GT;INT is_writable_address(无效* P){
    // 去做
}无效FUNC(字符* S){
    如果(is_writable_address(多个)){
        * S ='×';
    }
}诠释主(){
    char *之S1 =富;
    S2的char [] =酒吧;    FUNC(S1);
    FUNC(S2);
    的printf(%S%S \\ n,S1,S2);
    返回0;
}


解决方案

我一般同意这些建议,这是一个坏主意。

这是说,鉴于该问题具有<大骨节病> UNIX 标签,经典的方式做到这一点的类UNIX操作系统是使用阅读()的/ dev / zero的

 的#include&LT; fcntl.h&GT;
#包括LT&;&unistd.h中GT;INT is_writeable(无效* P)
{
    INT FD =打开(/开发/零,O_RDONLY);
    诠释可写;    如果(FD℃,)
        返回-1; / *不应该发生* /    可写=读(FD,P,1)== 1;
    关闭(FD);    返回可写;
}

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

解决方案

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

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

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