6

For this function:

void foo_ref(const int& i)
{
  cout << i << endl;
}

It's failed when I call it in gdb:

(gdb) call foo_ref(5)
Attempt to take address of value not located in memory.

Of course, in this simple example there's no need to use reference as parameter. If I use a normal "int", no problem then.
Actually the real example is a template function, like this:

template<class T>
void t_foo_ref(const T& i)
{
  cout << i << endl;
}

When "T" is "int", I have the problem mentioned above.

Is it a bug in gdb? Or is it possible I could call such function in gdb?

vicshen
  • 129
  • 2
  • 7

2 Answers2

15

It is possible, though not in an intuitive fashion (I would still classify this as a bug).

You need an actual memory region (a variable, or something heap-allocated).

(gdb) p (int *) malloc(sizeof(int))
$8 = (int *) 0x804b018
(gdb) p * (int *) 0x804b018 = 17
$9 = 17
(gdb) p t_foo_ref<int>((const int&) * (const int *) 0x804b018 )
17
$10 = void
(gdb)
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
0

5 is a literal and when you pass it to the function the compiler tries to store it in the address allocated for the function parameter i. But since i is a reference there is no where 5 can be stored in memory thus your error.

giorashc
  • 13,691
  • 3
  • 35
  • 71