thoni56
thoni56

Reputation: 3335

GDB showing incorrect function arguments on entry to C function

Debugging a C program with GDB I'm seeing the following (shortened):

(gdb)
1808            found = readOptionFromFile(options_file,...
(gdb) p options_file
$1 = (FILE *) 0xa812140
(gdb) s
readOptionFromFile (file=0x0, ...) at options.c:376
376 bool readOptionFromFile(FILE *file, ... {
(gdb) p file
$2 = (FILE *) 0x0
(gdb) n
378         int len, argc, i, c, isActiveSection, isActivePass, passn=0;
(gdb) p file
$3 = (FILE *) 0xa812140
(gdb)

Note that after stepping into the function GDB presents the arguments, particularly the formal argument file, as 0x0, which is not what I'd expect since the actual argument options_file was printed to be 0xa812140 just before making the call. Even printing it at this point shows this incorrect value. However, after a next a subsequent p of it shows the value 0xa812140 again.

I can understand this from a technical perspective (function prologues, stack frames and such) but as a user I'd really want correct output from GDB. Is this known/expected behaviour or a bug?

I'm using GNU gdb (Ubuntu 8.3-0ubuntu1) 8.3 on

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=19.10
DISTRIB_CODENAME=eoan
DISTRIB_DESCRIPTION="Ubuntu 19.10"

(Actually on WSL)

Upvotes: 3

Views: 792

Answers (1)

thoni56
thoni56

Reputation: 3335

Although the GCC manual explicitly says:

-O0
    Reduce compilation time and make debugging produce the expected results.
    This is the default.

Of course, you could debate the "expected results" part...

But it also goes on to state

-Og
    Optimize debugging experience. -Og should be the optimization level of choice
    for the standard edit-compile-debug cycle, offering a reasonable level of
    optimization while maintaining fast compilation and a good debugging experience. 
    It is a better choice than -O0 for producing debuggable code because some
    compiler passes that collect debug information are disabled at -O0.

Using -Og should solve the issue.

UPDATE: I found that the best option for debugging might often actually be -O0 since -Og allows for many variables to be optimized out because of the as-if rule. There is an issue about this from 2016.

Upvotes: 3

Related Questions