Consider the following three C functions:
int x = 10;
*px = 10;
px = (int*) malloc (sizeof(int));
*px = 10;
Which of the above three functions are likely to cause problems with pointers?
$[P1]$ may cause an error because function is returning the address of locally declared variable.
$[P2]$ will cause a problem because px is an int pointer that is not assigned with any address and we are doing dereferencing.
$[P3]$ will work because memory in bytes of size of int will be reserved and its address will be stored in px that can be further use, once function execution completes, this m/m will still exist in Heap until we free it using $free()$ function.
Hence, answer is (C).
In P3,can someone explain if malloc() returns null and we do initialization of px there....won't that lead to an error as we are trying to initialize a memory which don't even exists?? Plz clarify then how P3 works fine here?
@ Anu007 plz can you look into it
Read question they asked: Which of the above three functions are likely to cause problems with pointers?
so this will clear that memory is there to allocate.
P3 might not work in case there isn't sufficient memory available in the system (in that case malloc would return NULL).
I agree that what I'm saying is a rare case, but a problem is still a problem, right ?
So, according to me, the correct answer should be (C).
@Arjun sir So, untill restart that memory is wasted??
@Anmol 300 books will be dispatched this month...