Question 8421 – Algorithms
December 16, 2023Mathematical-Reasoning
December 17, 2023Pointers
Question 2
|
Consider the following three C functions:
[PI] int*g(void) { int x = 10; return(&x); } [P2] int*g(void) { int*px; *px = 10; return px; } [P3] int*g(void) { int*px; px = (int *) malloc(sizeof(int)); *px = 10; return px; }
Which of the above three functions are likely to cause problems with pointers?
Only P3
|
|
Only P1 and P3
|
|
Only P1 and P2
|
|
P1, P2 and P3
|
Question 2 Explanation:
[P1] → May cause error because the function is returning the address of locally declared variable.
[P2] → It will cause problem because px is in int pointer that is not assigned with any address and we are doing dereferencing.
[P3] → It will work because memory will be stored in px that can be use further. Once function execution completes this will exist in Heap.
[P2] → It will cause problem because px is in int pointer that is not assigned with any address and we are doing dereferencing.
[P3] → It will work because memory will be stored in px that can be use further. Once function execution completes this will exist in Heap.
Correct Answer: C
Question 2 Explanation:
[P1] → May cause error because the function is returning the address of locally declared variable.
[P2] → It will cause problem because px is in int pointer that is not assigned with any address and we are doing dereferencing.
[P3] → It will work because memory will be stored in px that can be use further. Once function execution completes this will exist in Heap.
[P2] → It will cause problem because px is in int pointer that is not assigned with any address and we are doing dereferencing.
[P3] → It will work because memory will be stored in px that can be use further. Once function execution completes this will exist in Heap.