int *mkarray1(int a, int b, int c) {
int arr[3];
arr[1] = b;
arr[2] = c;
gda
EoHa
arr
460110
ptr
return p; }
// Code for other_function() omitted.
int main() {
int *ptr = mkarray1(10, 20, 30); other_function(); y printf(“%d %d %d\n”, ptr[0], ptr[1], ptr[2]);
}
Cha
CSC209H Worksheet: Stacks and Heaps
1. Trace the memory usage for the program below. We have set up both stack frames for you, and the location of the heap.
Section
Heap
stack frame for mkarray1
arr[0] = a;interning int *p = arr;
Address
Value
Label
#include
#include
#include
0x244 0x248
freecptr
rycamallocGreoffin
L
TT En
a
2. The program in part 1 will not work correctly. Notice the call to other function. Explain to your partner why the program doesn¡¯t work. Fix the mkarray1 function, and trace it again.
3. Once you¡¯ve fixed the code, add a statement to your program to deallocate the memory on the heap as soon as possible.
stack frame
for main
0x23c E7 0x240
30
. . 0x454
0x458
0x45c
0x460
0x464
0x46c
0x470
0x474
0x478
0x47c
0x480
0x484
0x488
0x48c
#include
#include
/* Build an array in dynamic memory to hold
multiples of x from x to x*x.
Return a pointer to this array.
*/
int *multiples(int x) {
}
return a; }
int main() {
int *ptr;
int size = 3;
0TH
o
int *a = malloc(sizeof(int) * x);
0x234
for (int i=0; i < x; i++) {
a[i] = (i+1) * x;
0x238
12
CSC209H Worksheet: Stacks and Heaps
4. Trace the memory usage for the program below. We have set up the stack frame for you, and the location of the heap.
0x240 0x244
.
0x470 0x470
0x474
0x478
0x47c
0x480
0x484
0x488
0x48c
Besides the changes described, do not make any other changes or additions to the code.
6. Trace the memory usage of your changed program. Explain the problem to your partner and then fix it by adding calls to deallocate the memory.
forLintj size
ptr = multiples(size);
stack frame for multiples
TEELA
for (int i=0; i