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.
following link is Kvs_Pgt_Question Paper...