Call Stack C Programming
Call Stack C Programming
A taste of compiling
void f()
{
int x;
g(&x);
}
int *f()
{
int x;
return &x;
}
int *f()
{
int *p = malloc(sizeof(int));
return p;
}
void f()
{
int x;
int **p = malloc(sizeof(int*));
*p = &x;
}
What is the scope of p?
What is the lifetime of p?
What is the lifetime of what p points to?
void f()
{
int x;
free(&x);
}
Some terminology
I
10
11
Push parameters
Then call function; this pushes the return address
This works.
It makes it very easy to have variable number of arguments, like
printf in C.
But: stack is slow; registers are fast.
Compromise: use registers when possible, spill into stack
otherwise
Optimzation (-O flags) often lead to better register usage
12
frame for f
13
...
2
argument
argument
argument
14
15
abc\0
10
12
10
frame for f
12
16
p
q
Stack
...
Heap
..
.
...
N bytes
17
10
...
...
12
...
Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt
18
12
...
...
...
Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt
19
12
...
...
...
Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt
20
Pointers vs references
21
22
...
...
2
Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt
23
24
10
12
g
f
code for f
25
26
27
28
29
base pointer
x
y
bp - 8
bp - 24
bp - 32
bp - 16
30
x 7 rdi
y 7 rsi
x 7 rbp 8
y 7 rbp 16
a 7 rbp 24
b 7 rbp 32
f:
pushq %rbp
movq %rsp, %rbp
movq %rdi, -8(%rbp)
movq %rsi, -16(%rbp)
movq -8(%rbp), %rsi
addq $42, %rsi
movq %rsi, -24(%rbp)
movq -16(%rbp), %rsi
addq $23, %rsi
movq %rsi, -32(%rbp)
movq -24(%rbp), %rsi
imulq -32(%rbp), %rsi
movq %rsi, %rax
popq %rbp
ret
31
f:
addq $42, %rdi
leaq 23(%rsi), %rax
imulq %rdi, %rax
ret
32