Cannot call function with reference parameter in gdb - c++

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?

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)

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.

Related

gdb "Attempt to take address of value not located in memory." when calling functions, even const

I get errors even though there is no modification on the objects, very simple expression, calling a method:
(gdb) p my_unordered_map.count(edge.target_node_id)
$6 = 1
(gdb) p my_unordered_map[edge.target_node_id]
Attempt to take address of value not located in memory.
also I have the same error while calling a const function:
class A {
Sub s;
X get_x () const {
return s.x;
}
};
(gdb) p a.get_x()
Attempt to take address of value not located in memory.
(gdb) p a.s.x
--works
I don't understand. So far, when evaluating an expression, I can rely on it not working.
The code is in a lambda. A is an argument, my_unordered_map is captured by reference.
(gdb 8.3)

Memory Address showing? C++

Not really sure what's going on here, I'm using Clion as my IDE which I don't believe has anything to do with this but I figured I'd add that information. My confusion comes from a function that I wrote
int Arry()
{
int Mynumbers [5] = {10};
std::cout << Mynumbers;
}
something simple. It should be assigning 5 integers the value of 10. But when I print out Mynumbers I am shown the memory address. Why is this happening, I thought that was what calling pointers was for. Thank you for your time.
Sincerely,
Nicholas
It is a bit complicated, and there are a few issues at play:
std::cout (actually, std::ostream, of which std::cout is an instance, does not have an overload of operator<< that understands plain arrays. It does have overloads that understand pointers.
In C++ (and C) an array name can be used as an expression in a place where a pointer is needed. When there is no better option, the array name will decay to a pointer. That is what makes the following legal: int a[10] = {}; int* p = a;.
The overload that takes a pointer prints it as a hexadecimal address, unless the pointer is of type char* or const char* (or wchar versions), in which case it treats it as a null terminated string.
This is what is happening here: because there isn't an operator<< overload that matches the array, it decays to the overload taking a pointer. And as it isn't a character type pointer, you see the hexadecimal address. You are seeing the equivalent of cout << &MyNumbers[0];.
Some notes:
void Arry() // use void if nothing is being returned
{
int Mynumbers[5] = {10}; // first element is 10, the rest are 0
//std::cout << Mynumbers; // will print the first address because the array decays to a pointer which is then printed
for (auto i : Mynumbers) // range-for takes note of the size of the array (no decay)
std::cout << i << '\t';
}
In C++, you can think of an array as a pointer to a memory address (this isn't strictly true, and others can explain the subtle differences). When you are calling cout on your array name, you are asking for it's contents: the memory address.
If you wish to see what's in the array, you can use a simple for loop:
for (int i = 0; i < 5; i++)
std::cout << Mynumbers[i] << " ";
The value of Mynumbers is in fact the adress of the first element in the array.
try the following:
for(int i=0; i<5;i++) {
cout << Mynumbers[i];
}

Why is the value of a pointer to a function 1 [duplicate]

This question already has answers here:
How to print function pointers with cout?
(7 answers)
Closed 6 years ago.
I understand functions like data items have addresses and the address of a function is the memory address where the stored machine language code for the function begins. I have this code;
#include <iostream>
using namespace std;
int x(int);
char * y(char *);
int main() {
x(5);
y("hello");
int (*p) (int); //pointer to function x
char * (*q) (char *); //pointer to function y
p = &x; //holds the address of function x
q = &y; //holds the address of function y
cout << p << endl;
cout << q;
return 0;
}
int x(int a) {
return (a * a);
}
char * y(char *b) {
return (b);
}
So is there a way i can force the cpu to execute a particular function before another using the function addresses?
Upon compiling, the program prints out both addresses as 1. I was expecting hexadecimal values like that of data items. even when I print the dereferenced values, I still get 1, what is going on?
Also, if both function addresses are 1, how does the cpu know which function to execute first?
EDIT:
one of my questions is left unanswered, which i find very important! Doesn't wholly make it a duplicate even though some are.
The std::cout will convert function pointers to a bool, and since the function pointer is non-zero, the value 1 is displayed.
To display as hex value, cast the function pointer to a void *, for example:
cout << (void*)p << endl;
You can retrieve these functions addresses by typing :
cout<< &p << endl << &q << endl;
The & operator gives you back the address of block memory in which the variable after the & operator is set.

Offset from a memory address

I was reading some code and I came across this example. What I don't understand is why the author uses an offset of 1 from both variables on the last line. At first glance I would assume this is illegal because it is referring to a possibly uninitialized memory area (and it could cause a segmentation fault). My head keeps telling me undefined behavior but is this really so?
static bool lt(wchar_t a, wchar_t b)
{
const std::collate<wchar_t>& coll =
std::use_facet< std::collate<wchar_t> >(std::locale());
return coll.compare(&a, &a+1, &b, &b+1) < 0;
}
The last line is the one in question. Why is it necessary that he's doing this, is it legal, and when should it be done?
It appears that the author just wanted to compare two characters using the current global locale.
Since std::collate<T>::compare uses [low, high) for the two ranges, adding 1 to the address of the parameters will simply cause the comparison to stop after only a is compared to b. There should be no invalid memory accesses.
what book are you reading,
plus it depends on what are you comparing too!
sometimes you need to compare an ID that happens to be in the beginning of buffer, and with a certain size.
Testing your function
#include <locale>
static bool lt(wchar_t a, wchar_t b)
{
const std::collate<wchar_t>& coll =
std::use_facet< std::collate<wchar_t> >(std::locale());
return coll.compare(&a, &a+1, &b, &b+1) < 0;
}
int main () {
bool b = lt('a', 'b');
return 0;
}
Inside the debugger
Breakpoint 1, main () at test.cpp:13
13 bool b = lt('a', 'b');
(gdb) s
lt (a=97 L'a', b=98 L'b') at test.cpp:6
6 std::use_facet< std::collate<wchar_t> >(std::locale());
(gdb) p &a
$1 = 0x7fffffffdddc L"a\001翿\x400885"
(gdb) p &a+1
$2 = 0x7fffffffdde0 L"\001翿\x400885"
From this I believe
the code is legal
but &a + 1 is referring to possibly uninitialized memory
From what gdb returns I tend to think taking the address of a wchar_t returns a char* thus &a (a is a wchar_t) is a char* to the start of the multibyte variable that is a and &a+1 returns pointer to the second byte. Am I correct?

where is the address that a function pointer stores

I know that a function pointer stores the address of a function.
int fun(int x){
//return something
}
int (pfun*)(int)=&fun;
int main(){
std::cout << &fun << "\n"; // this print out 1
std::cout << fun << "\n" ; // this print out 1
std::cout << &pfun << "\n"; // this print out 0x0022ff40
std::cout << pfun << "\n" ; // this print out 1
}
So my questions are :
1) if the fun() doesn't even have an address how can pfun does point to fun().
2) for example in dynamic binding when I use a pointer function at runtime. does the compiler change pfun value to a real pointer like 0X..... so that at runtime will know which function to call since the names doesn't existe after compilation?
The expressions fun and &fun have the same meaning: &fun which is equivalent to the value stored in pfun, so it is no wonder that the three of them yield the same output. &pfun is the address of the pointer, which is the address of the variable.
Now the question is why 1... well, the answer is that there is no overloaded operator<< that takes an std::ostream and a function pointer, so the compiler tries to find the best match among the existing overloads which happens to be bool (a function pointer is implicitly convertible to bool). The function pointer will be converted to false only if the function pointer is null, which is not the case. The true value is finally printed as 1 (you can check this by doing: std::cout << std::boolalpha << fun which will print true).
If you want to obtain the actual address of the function (in this process) you can force the cast to a void pointer and print the result. This might not be technically correct, but it will give you a number different than 1... Note that the value might differ in different runs and basically has no meaning at all.
operator<< does not have an appropriate overload for printing function pointers. Try this instead.
#include <iostream>
void fun() {}
void (*pFun)() = &fun;
int main ()
{
std::cout << (void*)pFun << "\n";
}