gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:29:54 26 4
gpt4 key购买 nike

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

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

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

最佳答案

我大体上同意那些认为这是个坏主意的人。

也就是说,鉴于问题有 UNIX 标记,在类 UNIX 操作系统上执行此操作的经典方法是使用 read() 来自/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;
}

关于c - 如何在运行时检查内存地址是否可写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14433468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com