本次代写是一个C/C++的限时测试
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 }