打印函数地址在 linux 上总是打印 1 [英] Printing function addresses always prints 1 on linux

查看:24
本文介绍了打印函数地址在 linux 上总是打印 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 C++ 程序来处理不同变量和函数的地址.

I'm developing a c++ program that is dealing with addresses for different variables and functions.

当我在基于 Linux 的操作系统上编译我的程序时,包括 main 在内的所有函数都获得了 1 的地址,而不是像其他变量一样的 8 位十六进制数,这在 Windows 中没有发生.

When I compiled my program on a Linux based OS, all functions including the main get the address of 1 instead of an 8 digit hexa number like other variables, which did not happen in Windows.

我写了一小段代码来解释这个问题

I wrote this small piece of code to explain the issue

#include <iostream>
using namespace std;
void Function1();
void Function1(){ 
}

int main(){
    int tmp;
    void (*a) ()=&Function1;
    cout<<a<<endl;
    cout<<&Function1<<endl;
    cout<<&main<<endl;
    return 0;
}

对于所有 3 个 cout 调用,输出为 1 而不是虚拟地址.

for all 3 cout calls, the output is 1 instead of the virtual address.

推荐答案

指针被转换为另一种类型,boolean,因为它是一个函数指针 &对于这些类型的参数,iostrem 库中没有 operator<< 的重载(因为此类类型的数量是无限的).指针指向某个非零地址,因为它已使用函数地址进行初始化 - 所以被转换为 1(只有 0x0 地址会给你布尔值 0).

Tthe pointer gets converted to another type, boolean, because it is a function pointer & there is no overloads of operator<< in iostrem library for these types of argument (because there is infinite number of such types). The pointer points to some non-zero address because it has been initialized with address of function - so gets converted to 1 (only 0x0 address would give you boolean 0).

要断言正确的行为,您应该将指针强制转换为 void*,这样您就可以对 void* 使用 operator<< 重载,其中

To assert correct behavior you should cast the pointer to void* so you can use operator<< overload for void* which is

ostream & operator <<( ostream &, const void * );

示例:

void Function1(){}

int main() {
    void ( *a) () = &Function1;
    cout << ( void*)( a) << endl;
    /* or better - being explicit about harshness of this design */
    cout << reinterpret_cast< void*> ( a) <, endl;
}

http://ideone.com/Fne4Mu

C++ 标准 n3337 § 4.12 布尔转换 [conv.bool]

C++ Standard n3337 § 4.12 Boolean conversions [conv.bool]

1 算术、无作用域枚举、指针或指针的纯右值to 成员类型可以转换为 bool 类型的纯右值.一个零值、空指针值或空成员指针值被转换假的;任何其他值都将转换为 true.类型的纯右值std::nullptr_t 可以转换为 bool 类型的纯右值;这结果值为假.

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

这篇关于打印函数地址在 linux 上总是打印 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆