Printf the current address in C program

后端 未结 8 1355
时光说笑
时光说笑 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条回答
  •  旧时难觅i
    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."

提交回复
热议问题