Lec 06 - Call Stacks, Arrays
Last updated
Last updated
Slides:
We can think of the frame as a portion of stack. The latter is a portion of the memory in our computer. The memory allocated to each function call is called a stack frame. When a function returns, the stack frame is deallocated and freed up for other uses.
Now, we introduce how to draw the stack fram using the following example
Below is the stack frame diagram when the stack frame for add()
is created.
We use the square bracket [
and ]
to indicate that the variable list
is an array. The number 10
indicates that marks
holds 10 long
values. The size of the array must be an integer value, not a variable.
Using this way to declare a pointer, its type long
means that this pointer (variable) stores the address of a variable of type long
.
Also, it is important for us to know how to draw the stack-frame diagram containing pointers. Below is an example,
Array Name Dacay means that after you define an array, and then you want to use the array name, the array name will decay into just a memory address, not a pointer variable!!!
Array is passed by reference in C. Consider the code below:
When we call foo
, we push the memory address of the array (i.e., of the first element of the array), on the stack. With this memory address, foo
can now read the elements of the array a[0]
and a[1]
, by accessing the memory of the array on the stack frame of main
. If foo
modifies to the array, then the array on the stack frame of main
is updated as well.
This mechanism of passing arguments into a function is called "pass by reference", as opposed to "pass by value", in which we make a copy of the variable on the stack.
Knowing that, let's take a closer look at the declaration of foo
, and gain some deeper understanding about passing array to a function in C.
Here, the parameter long a[2]
, as you can see from the stack frame figure, actually creates a new pointer variable called a
on foo
's stack frame. And the content/value of the pointer a
is the memory address of the array a
which is on the main
's stack frame.
This informs us that in C, whenever we pass an array to a function, we are
create a local pointer variable in that function's stack frame
when we call the function (usually we will pass the memory address of the array using Array Name Decay), then the address of the array we passed will be stored in this local pointer variable.
If you really want to let the array name become a pointer, see
This is tested in in Final (AY24/25)!