Matt wanted to flex his C programming skills by playing with structs and unions.
ID: 3600844 • Letter: M
Question
Matt wanted to flex his C programming skills by playing with structs and unions. He devised the following code:
A. What is the output of the two print statements in lines 38 and 42? Explain this result.
B. In Part A, if the expected result differed from the actual result, how might you change the existing code to work as intended?
C. Show the partitioning of the bar_t struct (i.e., show the number of bytes dedicated to each field).
D. How many bytes does the bar_t struct require in total?
E. Using the following assembly code compiled by GCC, draw the stack frame for do_something2.
You must show each member field for any composite structures.
5 typedef union foo short long long int y char z; 7 10 foo t 12 typedef struct bar 13 E foo t foo stuffs [3]: char msg [64]; 16 ) bar t 18 void do_somethingl (bar_t a_bar) 19 E 20 21 strcpy (a bar msg, "do somethingl did something!") 23 bar 24 25 26 27 28 29 30 void main (int argc, char argvi) 31 32 t do something2 (void) bar t bar strcpy (bar msg, "do_something2 did something!"); return &bar; bar t fun (bar t *) malloc (1 * sizeof (bar t)); strcpy (fun-msg, "If only something would happen. ..") ; 34 35 36 37 38 39 // do somethingl do_somethingl (fun) printf( "do something! result: %s ", fun->msg); // do something2 fun do something2 ) printf( "do something2 result: %s ", fun->msg);Explanation / Answer
A)
The output of the two print statements in lines 38 and 42 will be like this :
If only something would happen...
do_something2 result : (some garbage value)
--> The first statement is like this because instead of sending a pointer of fun(fun) as pass by address we are sending the value inside it (*fun) as pass by value, thus changes in the function do_something1 wont make changes in fun.
--> The second line output is a garbage value because the bar variable in the function do_something2 is a local function and gets destroys when the control gets uut of the function thus &bar is referencing to a garbage value in the memory.
B)
code after changes :
#include <iostream>
#include <string>
typedef union foo
{
short *x;
long long int y;
char z;
} foo_t;
typedef struct bar
{
foo_t foo_stuffs[3];
char msg[64];
}bar_t;
void do_some1(bar_t *a_bar) // recieve the address of fun
{
strcpy_s(a_bar->msg, "do_somethng1 did something");
}
bar_t *do_some2(void)
{
static bar_t bar; // made a static variable
strcpy_s(bar.msg, "do_somethng2 did something");
return &bar;
}
void main(int argc, char* argv[])
{
bar_t *fun = (bar_t *)malloc(1 * sizeof(bar_t));
strcpy_s(fun->msg, "If only something would happen");
do_some1(fun); // pass the address of the fun variable
printf("do_something1 result: %s ", fun->msg);
fun = do_some2();
printf("do_something2 result: %s ", fun->msg);
}
C)
size of foo_t foo_stuffs[3] = 24
size of char msg[64] = 64
D)
size of bar_t = 88