2014-11-02 87 views
0

我有以下C程序,我想通過更改內存地址來更改變量secret。你能不能給我一個例子,我應該給以下兩個輸入來完成這個。任何幫助將大大appriciated更改存儲在變量中的內存地址C

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

如果可以的話,請告訴我用一個例子

+0

this line:scanf(「%p」,(void **)&value);將值的地址作爲void **進行投射。 scanf只關心地址和格式轉換,所以(無效**)是無用的 – user3629249 2014-11-02 11:20:43

+0

寫一些用戶提供的地址(一些隨機地址)是一個很好的方式來崩潰程序,可能是一個seg故障。 – user3629249 2014-11-02 11:22:13

回答

0

只需將printf("Address of secret is: %p", &secret);加上其他任何東西,然後當您運行該程序時,將第一個輸入的實際地址打印出來(&祕密),第二個輸入爲程序「1337beef」。例如,在我的機器上,它聲明可變機密位於0x804a02c,因此對於第一個輸入,我給了它「804a02c」,對於第二個「1337beef」,因此它輸入了if語句。玩的開心。

1

製作,打印的secret地址的變化。編譯並運行變體程序。

編輯:地址和分配的細節是特定於實現的。所以沒有辦法從C標準中發現這個數字。由printf("%p",...(並受scanf("%p",...影響)返回的值取決於特定的操作系統以及編譯器的特定設置。例如,我的Windows機器上有兩個版本的gcc,一個在Cygwin下,另一個在MinGW下。如果printf("%p",some_static_variable)在兩種環境中都打印相同的值,那將會非常令人驚訝。