The following piece of code always gives garbage value as output. I am aware of the reasoning behind it as a dangling pointer is created which still points to the memory location which is freed and reoccupied by a garbage value hence dereferencing it should also give the same garbage value.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int *p = (int*)malloc(sizeof(int));
*p = 10;
free(p);
cout<<*p;
}
but applying the same analogy to the following code should also give a garbage value but instead it is always giving segfault. Is there anyway to tell when we will get a segfault and when we will get a garbage value?
#include<bits/stdc++.h>
using namespace std;
int*myv()
{
int a = 90;
return &a;
}
int main()
{
int*p = myv();
cout<<*p;
}
Also, it will be a great help if somebody could concisely explain segmentation fault and the mechanism involving allocation-deallocation of memory in simpler language.