Home > Blockchain >  Get return value of function when last called, without calling it again
Get return value of function when last called, without calling it again

Time:04-07

I am new to using gdb.

I have a function, which I will call a() that gives a different value every time it is called. Another function add_to_array uses a() as a parameter. Here is an example:

add_to_array(a())
add_to_array(a())
add_to_array(a())

How could I see what the return values of a() were each time it was called?

CodePudding user response:

How could I see what the return values of a() were each time it was called?

If you are currently stopped before e.g. the last call to add_to_array(), and are interested in what value the first call to a() returned, the only way to know that (with GDB) is to examine what's in the array (to which add_to_array() adds values. GDB can't "go back in time" and can't keep track of every value that ever changed.

But if you just want to observe these values on re-run of the program, simply set a breakpoint on add_to_array, and (if your program is built with debug info -- usually the -g flag), GDB will stop and print the parameter value every time.

You may also be interested in a replay debugger, which can go back in time and which can answer the question directly.

CodePudding user response:

In addition to Employed Russian's excellent answer, you could instrument the code this way:

#define VALUES_HISTORY_LEN  65536
int a_values_history[VALUES_HISTORY_LEN];
int a_values_index;
int add_values_history[VALUES_HISTORY_LEN];
int add_values_index;

// this will store up to VALUES_HISTORY_LEN values previously returned by a()
#define a() (a_values_history[a_values_index   % VALUES_HISTORY_LEN] = (a)())

// this will store up to VALUES_HISTORY_LEN values previously passed to add_to_array()
#define add_to_array(x)  (add_to_array)(add_values_history[add_values_index   % VALUES_HISTORY_LEN] = (x))
  • Related