How to inspect the return value of a function in GDB?

I imagine there are better ways to do it, but the finish command executes until the current stack frame is popped off and prints the return value -- given the program

int fun() {
    return 42;
}

int main( int argc, char *v[] ) {
    fun();
    return 0;
}

You can debug it as such --

(gdb) r
Starting program: /usr/home/hark/a.out 

Breakpoint 1, fun () at test.c:2
2               return 42;
(gdb) finish
Run till exit from #0  fun () at test.c:2
main () at test.c:7
7               return 0;
Value returned is $1 = 42
(gdb) 

The finish command can be abbreviated as fin. Do NOT use the f, which is abbreviation of frame command!


Yes, just examine the EAX register by typing print $eax. For most functions, the return value is stored in that register, even if it's not used.

The exceptions to this are functions returning types larger than 32 bits, specifically 64-bit integers (long long), doubles, and structs or classes.

The other exception is if you're not running on an Intel architecture. In that case, you'll have to figure out which register is used, if any.