Exploring Formal Arguments in the Stack

17 Feb 2023 Balmiki Mandal 0 C Programming

Exploring Formal Arguments in the Stack

In C programming, formal arguments (also known as parameters) of a function are typically passed via the stack or registers, depending on the calling convention being used and the architecture of the system. Here, I'll focus on explaining how formal arguments are passed and managed on the stack.When a function is called, its formal arguments are usually placed onto the stack. The caller is responsible for pushing the arguments onto the stack before transferring control to the called function. The called function then accesses these arguments from the stack.Let's take a look at an example:

c programming language
#include <stdio.h>
int add(int a, int b) {
    return a + b;
}

int main() {
    int x = 5, y = 3;
    int result = add(x, y);
    printf("Result: %d\n", result);
    return 0;
}

In this example, when the add function is called from the main function, the values of x and y are passed as arguments. These values are pushed onto the stack before the control is transferred to the add function. Inside the add function, the values of a and b are accessed from the stack, and the addition is performed.

Here's a simplified step-by-step breakdown of the process:

  1. The main function pushes the values of x and y onto the stack as arguments to the add function.
  2. The add function's stack frame is set up, and space is allocated on the stack for its local variables and formal arguments.
  3. Inside the add function, the values of a and b are accessed from the stack.
  4. The addition operation is performed using the values of a and b.
  5. The result of the addition is stored in a register (like EAX on x86) or returned in another designated way.
  6. The stack space for the add function's stack frame is deallocated as the function returns.

It's important to note that the actual details of how arguments are passed and how stack frames are managed can vary based on factors such as the calling convention used by the compiler and the architecture of the system (x86, x86-64, ARM, etc.).Different calling conventions might use registers to pass arguments if the number of arguments is small and they can fit in registers. However, if there are more arguments or if the arguments are larger in size, they are often passed on the stack.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.