Printf the current address in C program

后端 未结 8 1334
时光说笑
时光说笑 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 
    
    #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.

提交回复
热议问题