Pointer Dereferencing


Take this C code as example:
// this is defined globally.
int globalVar;
// These lines of code are part of some function
int b;
int * ptr;
ptr = &globalVar;
*ptr = 100;
b = *ptr;

Generated assembly code:
movl    $globalVar, -4(%ebp)
movl    -4(%ebp), %eax
movl    $100, (%eax)
movl    -4(%ebp), %eax
movl    (%eax), %eax
movl    %eax, -8(%ebp)
Location of local variables of the stack (local variables are explained here)
ptr => -4(%ebp)
b => -8(%ebp)
The use of registers as temporary memory is described here
Comments on generated assembly code:
# ptr = &globarVar
    movl    $globalVar, -4(%ebp)

# tmp = ptr
    movl    -4(%ebp), %eax

# *tmp = 100
    movl    $100, (%eax)

# tmp = ptr
    movl    -4(%ebp), %eax

# tmp = *tmp
    movl    (%eax), %eax

# b = tmp
    movl    %eax, -8(%ebp)

up

Want to learn (C/C++ internals) directly from the author using video call? Learn more

Do you collaborate using whiteboard? Please try Lekh Board - An Intelligent Collaborate Whiteboard App