retagged by
11,759 views
52 votes
52 votes

The most appropriate matching for the following pairs$$\begin{array}{|ll|ll|}\hline X: & \text{m = malloc(5); m = NULL;} & 1: & \text{using dangling pointers} \\\hline  Y: & \text{free(n); n -> value = 5;} & 2: & \text{using uninitialized pointers} \\\hline   Z: & \text{char *p , *p = ‘a’ ; } & 3:  & \text{lost memory} \\\hline \end{array}$$ is:

  1. $X - 1 \ \  Y - 3 \ \  Z - 2$
  2. $X - 2 \ \  Y - 1 \ \  Z - 3$
  3. $X - 3 \ \  Y - 2 \ \  Z - 1$
  4. $X - 3 \ \  Y - 1 \ \ Z - 2$
retagged by

3 Answers

Best answer
88 votes
88 votes

Answer is (D).

$X: m = NULL$; makes the pointer $m$ point to $NULL$. But the memory created using $malloc$ is still there and but cannot be used as we don't have a link to it. Hence, lost memory

$Y: n$ is freed and so pointer $n$ is now pointing to an invalid memory making it a Dangling pointer.

$Z: p$ is not initialized. $p = malloc(sizeof(char))$; should have been used before assigning '$a$' to $*p$.

edited by
25 votes
25 votes

Dangling Pointer:- A pointer pointing to a memory location that has been deleted (freed) OR which is not valid for the type of object(int, char, struct...) you want to store at that address. This is known as dangling pointer error, But this error will only occur when you try to reach that deleted or invalid memory again. Example-

int *ptr = (int *)malloc(sizeof(int));
free(ptr);   // After this free call, ptr becomes a dangling pointer(Free() function uses only address so ptr will pass the address of memory allocated by malloc function.)
ptr = NULL; // ptr is no more a dangling pointer

Uninitialized Pointer:- Pointers are created to work around with the addresses, so when we declare a pointer int *p; program creates a pointer which initially points to some random location in the memory. It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system. and now if we try to store some value into uninitialized pointer address it will through error  *p=10;  But if we give some address to the pointer, it got initialized like  *p= &x;

Lost Memory:- When a pointer or variable stores an address of some memory location and if it accidentally lost the address, This condition is know as lost memory.   

Option D is correct.

 

edited by
1 votes
1 votes

Uninitialised pointers are also know as Wild pointers.

int x=10;

int *p; // p is a wild pointer 

p=NULL; // now p is not a wild pointer

Answer:

Related questions