60 40i
x
I whenfunreturns
FtIEJzo
800
int *i;
i = malloc(sizeof(int)); 8
} y void fun(int **i) {
24
40
whenfreed jwwhuenntfeeeoYrms
}
int m.aOin()y{
}
int i[5] = {4,5,2,5,1};
f
when
u
n(i)
;
ename_ofazqoffgihHsfforma.n
mainends
inte mallock to
int main() { pointer omelemnent
*i = malloc(sizeof(int)*7);
}
int main() {
int *i;
fun(&i);
free(i); }
in
4×7 g
es
hesatpfrfn for
CSC209H Worksheet: malloc Basics
1. Each time a variable is declared or memory is otherwise allocated, it is important to understand how much memory is allocated, where it will be allocated and when it will be de-allocated. Complete the table below. (Note: some of the programs allocate more than one block of memory.)
Code Fragment
int main() {
int i;
}
int fun() {
float i; }
int main() {
fun();
}
int fun(char i) {
…
}
int main() {
fun(¡¯0a¡¯); }
int main() {
char i[10] = {¡¯h¡¯,¡¯i¡¯};
}
int main() {
char *i; }
int main() {
int *i;
}
int fun(int *i) {
…
Space?
sizeof(int)
siteofffloat 4
siteofCchar speoffchar
sifeoffchart
sigeoffint
speoffint
Where?
stack frame for main
De-allocated when?
when program ends
sf forfun whenfunterminate
sf forfun
Sf
Sf
when funterminate when program
for
for fun
main
endg
Sf main
ends
whenprog
CSC209H Worksheet: malloc Basics
2. Trace the memory usage for the program below up to the point when initialize is about to return. We have set up both stack frames for you, and the location of the heap.
Section
Heap
stack frame for initialize
Address
0x23c 0x240
0x244 0x248
TMEI
Value
FO I
Label
#include
#include
.
.
// Initialize two parallel lists.
void initialize(int *a1, int *a2, int n) {
for (int i = 0; i < n; i++) {
a1[i] = i;
a2[i] = i; }
}
0x454
0x458
0x45c
0x460
0x464
0x46c
0x470
0x474
0x478
0x47c
0x480
0x484
0x488
0x48c
al
a2 heelin
int main() {
int numbers1[3];
int *numbers2 = malloc(sizeof(int) * 3);
initialize(numbers1, numbers2, 3);
for (int i = 0; i < 3; i++) {
printf("%d %d\n",
numbers1[i], numbers2[i]);
}
free(numbers2);
return 0; }
hog
stack frame for main
numbersI
107 Hel
numbers z i
void Ancient arr
Mallock 4 11
siteof Lint fun0 600807
T
arr arr
int
int
fun
10
arr
mainC
Mama
oxo
a
a a
NULL