Printf the current address in C program

后端 未结 8 1330
时光说笑
时光说笑 2021-02-04 12:27

Imagine I have the following simple C program:

int main() {

int a=5, b= 6, c;
c = a +b; 
return 0;
}

Now, I would like to know the address of

相关标签:
8条回答
  • 2021-02-04 12:50

    Using gcc on i386 or x86-64:

    #include <stdio.h>
    
    #define ADDRESS_HERE() ({ void *p; __asm__("1: mov 1b, %0" : "=r" (p)); p; })
    
    int main(void) {
        printf("%p\n", ADDRESS_HERE());
        return 0;
    }
    

    Note that due to the presence of compiler optimizations, the apparent position of the expression might not correspond to its position in the original source.

    The advantage of using this method over the &&foo label method is it doesn't change the control-flow graph of the function. It also doesn't break the return predictor unit like the approaches using call :) On the other hand, it's very much architecture-dependent... and because it doesn't perturb the CFG there's no guarantee that jumping to the address in question would make any sense at all.

    0 讨论(0)
  • 2021-02-04 12:52

    In gcc, you can take the address of a label using the && operator. So you could do this:

    int main() 
    {
        int a=5, b= 6, c;
    
        sum:
            c = a+b;
    
        printf("Address of sum label in memory: %p", &&sum);
        return 0;
    }
    

    The result of &&sum is the target of the jump instruction that would be emitted if you did a goto sum. So, while it's true that there's no one-to-one address-to-line mapping in C/C++, you can still say "get me a pointer to this code."

    0 讨论(0)
提交回复
热议问题