[英]Changing memory address stored in a variable in C
I have the following C
program and I would like to change the variable secret
by changing the memory address. 我有以下
C
程序,我想通过更改内存地址来更改变量secret
。 Can you please show me with an example, what I should put for the following two input to accomplish this. 您能举一个例子给我看一下,为完成以下两个步骤,我应该输入些什么。 Any help would be greatly appriciated
任何帮助将不胜感激
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
unsigned secret = 0xdeadbeef;
int main(int argc, char **argv){
unsigned *ptr;
unsigned value;
printf("Welcome! I will grant you one arbitrary write!\n");
printf("Where do you want to write to? ");
scanf("%p", &ptr);
printf("Okay! What do you want to write there? ");
scanf("%p", (void **)&value);
printf("Writing %p to %p...\n", (void *)value, (void *)ptr);
*ptr = value;
printf("Value written!\n");
if (secret == 0x1337beef){
printf("Woah! You changed my secret!\n");
exit(0);
}
printf("My secret is still safe! Sorry.\n");
}
If you can, please show me with an example 如果可以,请举例说明
Make a variation that prints the address of secret
. 进行更改以打印
secret
的地址。 Compile and run the variant program. 编译并运行变体程序。
Edit: The details of addresses and allocations are implementation-specific. 编辑:地址和分配的详细信息是特定于实现的。 So there's no way to discover this number just from the C standard.
因此,无法仅从C标准中发现此数字。 The value returned by
printf("%p",...
(and affected by scanf("%p",...
) is dependant upon the specific OS, and the particular setup of the compiler. For example, I have two versions of gcc
on my Windows machine, one under Cygwin and one under MinGW. And it would be very surprising if printf("%p",some_static_variable)
printed the same value in both environments. printf("%p",...
(并受scanf("%p",...
)影响)返回的值取决于特定的操作系统和特定的编译器设置。例如,我有两个Windows计算机上的gcc
版本,一个是Cygwin下的版本,一个是MinGW下的版本,如果在两个环境中printf("%p",some_static_variable)
打印相同的值,这将非常令人惊讶。
Just add a printf("Address of secret is: %p", &secret);
只需添加一个
printf("Address of secret is: %p", &secret);
above anything else, then when you run the program, give the first input the actual address it printed out (&secret), and for the second input give the program "1337beef". 首先,在运行程序时,为第一个输入提供打印出的实际地址(&秘密),为第二个输入提供程序“ 1337beef”。 For example, on my machine, it stated that the variable secret is located at 0x804a02c, so for the first input I gave it "804a02c" and for the second "1337beef" so it enters the if statement.
例如,在我的机器上,它声明变量secret位于0x804a02c,因此对于第一个输入,我给它提供了“ 804a02c”,对于第二个输入,给了它“ 1337beef”,因此它输入了if语句。 Have fun.
玩得开心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.