Randomblue
Randomblue

Reputation: 116273

How to declare a variable in the scope of a given function with GDB?

I know that gdb allows for an already declared variable to be set using the set command.

Is it possible for gdb to dynamically declare a new variable inside the scope of a given function?

Upvotes: 32

Views: 31461

Answers (3)

Illia Bobyr
Illia Bobyr

Reputation: 780

You can dynamically allocate some space and use it to store a new variable. Depending on what you mean by "scope of the current function" it may not be what you want.

But here is how it looks like, when you have function func() that takes a pointer to an output parameter:

set $foo = malloc(sizeof(struct funcOutStruct))
call func($foo)
p *$foo
call (void) free($foo)

Upvotes: 38

unwind
unwind

Reputation: 399793

For C (and probably C++) code, that would be very hard, since doing so in most implementations would involve shifting the stack pointer, which would make the function's exit code fail due to it no longer matching the size of the stack frame. Also all the code in the function that accesses local variables would suddenly risk hitting the wrong location, which is also bad.

So, I don't think so, no.

Upvotes: 19

jasonxiaole
jasonxiaole

Reputation: 81

that's how I used to print variables

(gdb) set $path=((ngx_path_t     **)ngx_cycle->paths.elts)[2]
(gdb) print *$path
    $16 = {
        name = {
            len = 29,
            data = 0x80ed15c "/usr/local/nginx/fastcgi_temp"
            },
        len = 5,
        level = {1, 2, 0},
        manager = 0,
        loader = 0,
        data = 0x0,
        conf_file = 0x0,
        line = 0
    }

Upvotes: 8

Related Questions