+ 3
What if we try to print dangaling pointer?
#include <stdio.h> #include<stdlib.h> int main() { int* p=(int*)malloc(sizeof (int)); printf ("%d",*p); return 0; } https://code.sololearn.com/c3lm96MGZL7a/?ref=app https://code.sololearn.com/c3lm96MGZL7a/?ref=app
12 Réponses
+ 10
By the term "dangaling pointer" do you intend "dangling pointer"? If so, do you mean a pointer that is uninitialized? If so, then you should presume the result will be unpredictable because the pointer will have whatever value was in memory at the time that its variable space was assigned.
Or do you mean a pointer whose reference memory has been freed? Again you should presume the result will be unpredictable. Though immediately it is likely that the memory will hold the same information as before it was freed, eventually some process will allocate that space and overwrite it.
Let us know whether this answers your question, or you meant something else.
+ 5
That's not a dangling pointer. Your code have no dangling pointer..
You just initialized memory and it's assigned a default value..
Edit : Dershil Jadav see this for what is dangling pointer and the precedings for accessing of those pointers in Program..
https://developerinsider.co/what-is-dangling-pointer-with-cause-and-how-to-avoid-it/amp/
+ 4
Please show your code. Nobody can say without knowing what the code is doing.
+ 4
Now with the code added to the question I see that this is a slightly different situation. Memory is allocated, but uninitialized. Yet it appears initialized anyway because it holds zero.
While zero is a typical value to expect for initialized memory (for example, from calloc), it is not necessarily a reliable result to expect from malloc. It could be a different value at another time, leftover from some previous use of that memory.
+ 4
After another edit to the linked code we do see a genuine dangling pointer because it is freed and then used again afterward to print the deallocated memory (and still uninitialized). I think we have covered this topic.
If you are uncertain about this still, then read the article linked by Jayakrishna🇮🇳. It is critically important to understand.
+ 3
You may get a segmentation fault.
+ 3
Your program may crash.
+ 1
Expect undefined behaviour as well as output I guess?
0
No I got my ans but I tried to print that but it gives output of 0 why that so...??
0
Done check it
0
Now check