How to modify memory contents using GDB?

CLinuxMemoryGdb

C Problem Overview


I know that we can use several commands to access and read memory: for example, print, p, x...

But how can I change the contents of memory at any specific location (while debugging in GDB)?

C Solutions


Solution 1 - C

The easiest is setting a program variable (see http://sourceware.org/gdb/current/onlinedocs/gdb/Assignment.html#Assignment">GDB: assignment):

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4

There's more. Read http://sourceware.org/gdb/current/onlinedocs/gdb/">the manual.

Solution 2 - C

As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20

This should work for any valid pointer, and can be cast to any appropriate data type.

Solution 3 - C

Expanding on the answers provided here.

You can just do set idx = 1 to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1 would not be valid.

This means that you should prefer the syntax: set variable idx = 1 or set var idx = 1.

Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.

(gdb) p idx = 1
$1 = 1

You can read more about gdb here.

Solution 4 - C

One of the most useful things is to change the value of Registers directly.

 0x000000000800088e <+67>:    lea    rdi,[rip+0x118]        # 0x80009ad

To change the value of rdi register:

 set $rdi = 0x8201010

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbitsView Question on Stackoverflow
Solution 1 - CNikolai FetissovView Answer on Stackoverflow
Solution 2 - CAndrew EdgecombeView Answer on Stackoverflow
Solution 3 - CJoão PortelaView Answer on Stackoverflow
Solution 4 - CBoRRisView Answer on Stackoverflow