Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 304
Randomblue Avatar asked Apr 23 '12 16:04

Randomblue


People also ask

How do I declare a variable in gdb?

You can create variables in the context of gdb for your convenience, like set $foo = ... and later reference $foo . Obviously such variables are in no way visible to the running code, however. it's not only for inspection. you can change variable values in gdb: stackoverflow.com/questions/3305164/….

Which command is used to determine the variable in gdb?

The ptype [ARG] command will print the type. Show activity on this post. This question may be related: vtable in polymorphic class of C++ using gdb: (gdb) help set print object Set printing of object's derived type based on vtable info.

What does P do in gdb?

The usual way to examine data in your program is with the print command (abbreviated p ), or its synonym inspect . It evaluates and prints the value of an expression of the language your program is written in (see section Using GDB with Different Languages).


2 Answers

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 free($foo) 
like image 50
Ilya Bobyr Avatar answered Sep 19 '22 18:09

Ilya Bobyr


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.

like image 34
unwind Avatar answered Sep 18 '22 18:09

unwind