gpt4 book ai didi

c - 将索引访问转换为指针访问

转载 作者:行者123 更新时间:2023-12-01 13:41:11 25 4
gpt4 key购买 nike

假设我有一个函数 int access_p_i(uintptr_t i) 可以访问p[i] 其中 char *p; 是一个全局变量。

char *p;
int access_p_i(uintptr_t i)
{
return printf("p[%lx]=%c\n", i, p[i]);
}

预期用途如下:

char buf[] = "abcde";
p = buf; /*set p once*/
access_p_i(3); //prints p[3]=d
access_p_i(2); //prints p[2]=c

假设我想劫持它(不修改函数)以获取绝对指针:

memset(&p,0,sizeof(char*)); /*set p once*/
access_p_i((uintptr_t)"d");
access_p_i((uintptr_t)"c");

这会是可移植且合法的 C 语言吗?

最佳答案

不,我认为这不太好。来自 ANSI/ISO 9899-1990,关于向指针添加或从指针中减去整数:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. Unless both the pointer operand and the result point to elements of the same array object, or the pointer operand points one past the last element of an array object and the result points to an element of the same array object, the behavior is undelined if the result is used as an operand of the unary * operator.

关于c - 将索引访问转换为指针访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40069345/

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