string 在 gdb 中,如何将字符串写入内存?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19503057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:07:59  来源:igfitidea点击:

In gdb, how can I write a string to memory?

stringgdb

提问by Balz Guenat

It is quite straightforward to write ints or hexadecimals to a memory address with gdb:

使用 gdb 将整数或十六进制写入内存地址非常简单:

(gdb) set {int}0x08040000 = 42
(gdb) set {int}0x08040000 = 0xffffffff

But how can I write chars or entire strings in a similarly simple fashion to memory? Right now I have to resort to translating the string to hex and then entering that, which is time consuming.

但是如何以类似的简单方式将字符或整个字符串写入内存?现在我不得不求助于将字符串转换为十六进制然后输入,这很耗时。

回答by FuriousGeorge

Say you have the following program:

假设您有以下程序:

int main(void){
    char[] person = "Bob";
    char[] p2 = "Alice";

    printf("Hello %s\n");
}

With GDB you could set a breakpoint in main, and change the person's name via:

使用 GDB,您可以在 main 中设置断点,并通过以下方式更改人名:

(gdb) set main::person = { 'S', 'a', 'm', 0x00 }

or more susinctly

或更直接地

(gdb) set main::person = "Sam"

If you want to set memory directly use:

如果要直接设置内存使用:

set {char [4]} 0x08040000 = "Ace"

I'm assuming that since you're poking memory with gdb you know what you're doing, so you know about setting the null bytes for strings etc. Keep in mind if you are trying to change values for an array and you try to put in a string that is longer than what was originally allocated, you have a really good chance that you're going to corrupt memory. (example trying to set main::person to "Dilbert" is going to cause problems

我假设,因为你用 gdb 戳内存你知道你在做什么,所以你知道为字符串等设置空字节。请记住,如果你试图更改数组的值并且你尝试放入一个比最初分配的字符串长的字符串,你很有可能会破坏内存。(例如尝试将 main::person 设置为“Dilbert”会导致问题

回答by Paul Beusterien

Use strcpy()

strcpy()

(gdb) p malloc(20)
 = (void *) 0x6ce81808
(gdb) p strcpy(, "my string")
 = 1827149832
(gdb) x/s 
0x6ce81808: "my string"