7,328 views

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$

in the beginning of the video we see that Memory allocated by a malloc(5) is drawn in memory blocks(“small square blocks”) but that is the work of calloc right? malloc allocates the entire block.

### Subscribe to GO Classes for GATE CSE 2022

$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$.

@Vasudha-Garg
nice explanation....
pls explain option a ) little bit more
m=malloc(5)  //m is pointing to memory location allocated by malloc function

m=null         //  now m is not pointing to anything, but memory is still allocated and now we dont have a link to access  the memory

therefore memory Lost.
well explained
Nice

Case X is also known as Memory Leak
edited by

p is not initialized, p=malloc(sizeof(char)); should have been used before assigning 'a' to ∗p.

Char *p= NULL;

*p= ‘a’;

Can we use this. I’m not totally sure… anyone??

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.