Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

Homework 3

Due: Monday, March 4, 2024

These problems should be done on your own. We’re not going to be grading them strictly (we’ll mainly look at whether you attempted them). But they will be reinforcing knowledge and skills, so you should totally work through them carefully.

Please save your answers as a single PDF file and upload it to Brightspace.

Question 1

Alice has learned that the function strncpy() can be used to copy a string. So she writes the following code to try it out. However, the result isn’t what she expects.

#include <stdio.h>

#include <string.h>

 

int main() {

char str1[4] = "1234";

char str2[4];

 

strncpy(str2, str1, sizeof(str2));

 

printf("str2 = %s\n", str2);

}

Can you explain this issue to Alice and help her correct it?

Question 2

Now, Alice wants to see if strncpy() can be used to copy other types of arrays. So she writes the following code. Since strncpy() only accepts char * arguments, she uses a trick: she casts the integer arrays to char * type.

#include <stdio.h>

#include <string.h>

 

int main() {

int arr1[4] = {1, 2, 3, 4};

int arr2[4];

 

strncpy((char *)arr2, (char *)arr1, sizeof(arr2));

 

printf("arr2 = ");

for (int i = 0; i < 4; ++i) {

printf("%d", arr2[i]);

}

printf("\n");

}

Once again, this code does not work: only the rst element of arr1 is copied to arr2.

(1) Can you explain to Alice what’s happening here?

(2) Instead of strncpy(), what function should be used to copy an array?

Question 3

When an interrupt or a system call transfers control to the operating system, a kernel stack area separate from the stack of the interrupted process is generally used. Why?

Question 4

In the following figure, three process states are shown.

In theory, with three states, there could be six transitions, two out of each state.

However, only four transitions are shown. Are there any circumstances in which either or both of the missing transitions might occur?