Search code examples
cfunctionpointerslow-level

What does a function look like in memory?


I'm starting to learn C, and I just learned about pointers to functions. This made me wonder, what does a function look like in memory? I mean, (correct me if I'm wrong) an int variable for example is just a chunk of 2/4 bytes, storing a certain whole number. But what does a function look like in memory? How do you convert operations such as if, while, malloc, etc into numbers or binary?


Solution

  • What does a function look like in memory?

    A function is a number of consecutive bytes. For instance in hex a function could be:

    A2 32 67 98 34 33 12 23 22 55
    

    These (hex) numbers represents instruction that the hardware, i.e. the CPU, can execute. The CPU decodes the values and finds out what it is going to do. In other words - which instructions to execute.

    Exactly how these numbers translate into instructions differs from CPU family to CPU family. Sometimes a single byte is a whole instruction. Sometimes it takes a number of bytes to make an instruction. To figure out how to translate the bytes into instructions, you need to consult the instruction set of the CPU being used.

    In some cases instructions are pretty simple. For instance "ADD register 1 and register 2", "JUMP-IF-ZERO register 3, address", "DECREMENT register 5", "LOAD register 1 from a memory address", "STORE register 1 to a memory address" and so on. But you can also find CPUs with pretty complex instructions.

    ? How do you convert operations such as if, while,

    By using a number of the simple instructions from the instruction set.

    Example: With the simple instructions I made up above and assuming that x is integer located at address 0x100 in memory, the C code:

    x = x - 1;
    if (x != 0)
    {
        x = x - 1;
    }
    

    could be something like

        LOAD reg1, 0x100  // Read x from memory address 0x100 into register 1
        DECREMENT reg1
        JUMP-IF-ZERO reg1, LABEL1
        DECREMENT reg1
    LABEL1:
        STORE reg1, 0x100 // Write x back to memory
    

    Notice that a specific C code often can be made in several ways on a specific CPU. Different compilers may generate a different sequence of instruction for the same C code.