Question

If I compile:

int *a;

void main(void)
{
    *a = 1;
}

and then disassemble main in cdb I get:

pointersproject!main:
00000001`3fd51010 mov     rax,qword ptr [pointersproject!a (00000001`3fd632f0)]
00000001`3fd51017 mov     dword ptr [rax],1
00000001`3fd5101d xor     eax,eax
00000001`3fd5101f ret    

So *a is symbolized by pointersproject!a. All good.

However, if I declare the pointer within main:

void main(void)
{
    int *a;
    a = 1;
}

I see that a is just an offset from the stack pointer (I believe), rather then the human-readable structure I'd expect (like, say pointersproject!main!a):

pointersproject!main:
00000001`3fd51010 sub     rsp,18h
00000001`3fd51014 mov     rax,qword ptr [rsp]
00000001`3fd51018 mov     dword ptr [rax],1
00000001`3fd5101e xor     eax,eax
00000001`3fd51020 add     rsp,18h
00000001`3fd51024 ret

This is probably as much about my understanding of what the compiler's done as anything else but: can anyone explain why the notation for a isn't what I expect?

(This inspired by musing while looking at x64 Windows Debugging: Practical Foundations by Dmitry Vostokov).

Was it helpful?

Solution

When a variable is defined inside a function, it is an automatic variable unless explicitly declared static. Such variables only live during the execution of the function and are normally allocated in the stack, thus they are deallocated when the function exits. The change you see in the complied code is not due to the change in scope but to the change from static to automatic variable. If you make a static, it will not be allocated in the stack, even if its scope is the function main.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top