Skip to content
systemcoding.dev
Debugging

Store temporary values in convenience variables with set $var

Keep temporary values in GDB convenience variables with set $var, so later commands can reuse a pointer or a computed number.

1 min read
Summarize in AI

A convenience variable is a GDB-side variable whose name starts with a dollar sign. It exists only in the debugger, never in the program, and it holds a value of any type, so you can save a pointer, a count or a whole struct while you keep stepping.

Text
(gdb) set $buf = request->body
(gdb) set $n = request->len
(gdb) p $n * 2
$1 = 8192
(gdb) x/s $buf
0x4052a0:	"name=alice"
(gdb) p $unset
$2 = void

The assignment copies the value at that moment, so $buf keeps the old pointer after the program frees it, which is exactly what you want when comparing before and after. An unset one prints void, not an error, so a typo in a name is silent; check with show convenience, which lists all of them, including GDB's own such as $_ and $bpnum.

Text
(gdb) set $limit = 10
(gdb) if $n > $limit
 >echo too big\n
 >end

They also work in breakpoint conditions and commands, which is how counters are built. Convenience variables are not typed by declaration: assigning an int and later a string changes the type, and an integer literal is held as int, so large values overflow at 32 bits unless you cast with (long). See convenience variables, GDB 16.

Taggedclinuxgdb
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.