Search code examples
pointersmemory-managementvirtual-memorydereference

How is a pointer distinguished from a normal variable in C , under the hood


How is the data pointed to by pointer which holds the virtual address accessed ?

How does the processor know that the content of a pointer is an address and not the data itself ?

Can somebody give me a step-by-step process ?


Solution

  • In short, C code that deals with pointers gets compiled to CPU Op codes that deal with addresses — so the digit — the physical machine code that performs an operation on a value, is simply a different instruction code from one that performs an operation on an address (pointer).

    The reality is more complicated than that of course. You can see in detail what happens to different (small) C programs by following the instructions in this stack overflow question How do you get assembler output from C/C++ source in gcc?

    On a deeper level, Operating systems and CPUs virtualise physical memory — so that an instruction that requests memory at address x, in hardware, uses a virtual lookup table to get memory from physical address y — this is a modern development that allows for security and memory management features like memory randomisation.