Best代写-最专业靠谱代写IT | CS | 留学生作业 | 编程代写Java | Python |C/C++ | PHP | Matlab | Assignment Project Homework代写

C/C++代写|Systems Programming in C and C++

C/C++代写|Systems Programming in C and C++



Answer ALL questions. Each question will be marked out of 20. The paper will be marked
out of 60, which will be rescaled to a mark out of 100.

Question 1

The question is about pointers and memory management in C.

(a) Will there be any memory leakage in the following program? Explain your answer.

1 int main()
2 {
3 int *A = (int *) malloc(sizeof(int));
4 scanf(“%d”, A);
5 int *B;
6 B = A;
7 free(B);
8 return 0;
9 }

(b) A programmer has written the following function with the aim to return a pointer
to an array of 10 random integers (int) to a caller function. There is a serious
problem with this code. Explain what is wrong, why it is a problem, and how it can
be fixed. Use this to write a correct version of the function without changing the
function-signature. Assume that the caller function of randomArray is responsible
for freeing any memory occupied by the array.

1 int* randomArray(void)
2 {
3 int array[10], i;
4 for (i = 0; i < 10; i++)
5 array[i] = rand();
6 return &array[0];
7 }

(c) Consider the following two C functions sum2Darray1 and sum2Darray2. Both of
them compute the sum of all the elements of an input 2-dimensional matrix. Which
one of them will be able to exploit memory hierarchy and thus achieve faster com
putation time? Explain your answer.

1 int sum2Darray1(int a[N][M])
2 {
3 int i, j, sum=0;
4 for(i=0;i<M;i++)
5 for(j=0;j<N;j++)
6 sum =sum + a[j][i];
7 return sum;
8 }
1 int sum2Darray2(int a[N][M])
2 {
3 int i, j, sum=0;
4 for(i=0;i<N;i++)
5 for(j=0;j<M;j++)
6 sum =sum + a[i][j];
7 return sum;
8 }

Question 2

The question is about concurrent programming.

(a) Consider a concurrent system with three processes P1, P2 and P3.

Provide a (semaphore based) solution to synchronize P1, P2 and P3 such that the
following constraints on execution order is satisfied:

• Statement B before Statement A,
• Statement A before Statement C

Provide a possible (deadlock free) trace of your solution.