631 views
1 votes
1 votes
MSQ

 

Consider the following C snippet:


#include <stdio.h>

int main() 
{
    int *ptr = (int*) malloc(100*sizeof(int));
    *ptr=33;
    printf("%d %d\n",ptr,*ptr); // Line X
    
    free(ptr);
    *ptr=37;
    printf("%d %d\n",ptr,*ptr);  // Line Y
    
return 0;

}

Which of the following is TRUE regarding “Line X” and “Line Y”

  1. Printed value of ptr (heap address) is same for both “Line X” and “Line Y”
  2. Printed value of ptr (heap address) is not same for both “Line X” and “Line Y”, as in Line Y, ptr is a dangling pointer and will print garbage value
  3. The value of *ptr (value at *ptr) is 37 in Line ‘Y’
  4. The value of ptr (value at *ptr) is 0 as in Line Y, the allocated heap is freed, and we cannot update it anymore, as ptr is now a dangling pointer

2 Answers

Best answer
2 votes
2 votes

Since in the code after freeing up the pointer variable ptr we are not assigning NULL to it, it is behaving in an undefined manner. So the given answer might not always be true because it will depend on the platform. 

Source of the Image: Dynamic Memory Allocation - How to play with pointers in C (codingame.com)… 

If we assign NULL to the ptr variable after freeing it up it works in the expected manner. 

Point to be Noted: If we assign NULL to the ptr variable before freeing it up, it can cause Memory Leak.

 

selected by
0 votes
0 votes




The answer is ‘1’ and ‘3’ any idea why?

Related questions

0 votes
0 votes
1 answer
2
Gurdeep Saini asked Feb 1, 2019
639 views
is it dangling pointer ?int main(void) { int* p;printf("%d",*p); return 0;} https://ideone.com/IN77el
0 votes
0 votes
1 answer
3
iarnav asked May 5, 2017
701 views
#include <stdio.h int*fun() { intx=5; return&x; } int main(){ int*p=fun(); fflush(stdin); printf("%d",*p); return0; }Please explain this code, how's it's working line by ...