Krista's Coding Corner

11.11.2012

What happens when you call a function?

Here is what happens after we come into such part of code where some function is called:

  1. Computer finds out in which memory address the wanted function is located.
  2. Depending on how much data is in the parameters for the function:
    • If there is only little, the parameters will be located to processor’s registers (memory) which is inside the processor.
    • If there is a lot of that data, the data is stored in main memory that can handle more data than register. In this case we just store where this data can be found (what addresses) into registers.
  3. Computer stores into the main memory (= into stack in this case), in which step in the program we are (to have a returning address). We don’t want to lose track on what we are doing that and start all over again.
  4. Computer jumps to the function (its location) and runs the function.
  5. After that the computer checks where we started and jumps back to the program that made the function call. To be precise: it jumps to the next code row and just continues. The computer also empties the processors register and main memory (if used) from the parameter information.

If you have a lot of function calls inside other function calls (inside if-loop is another if, where is another if and so on), you will be using a lot of memory (RAM! Not the storage space). Try to avoid that as the memory might run out… :)

Same happens if you have recursive function calls. Some programming languages may see that you have recursions going on, and won’t duplicate all returning addresses and parameters to the memory (this makes it possible to have loops in languages that actually don’t have loop possibilities at the first place). This feature is called Tail call elimination.

Other problem is: if the memory where the data from step 3 gets messed up (some piece of program writes there something else), your program might do just about anything as the returning address is incorrect! One of the computer cracking techniques is that we change the returning address (step 3) into something else. For example, the cracker want’s the computer to start running his code. This is one of the most common ways how viruses and Trojans work, so beware :)

blog comments powered by Disqus