In gdb, how can I write a string to memory

gdbstring

It is quite straightforward to write ints or hexadecimals to a memory address with 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.

Best Answer

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) 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