0

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
Anke
  • 19
  • 5
  • 8
    Both of these have _undefined behavior_. That means you have _no guarantee whatsoever_ on what the programs will do. – user17732522 May 13 '22 at 19:26
  • So, you want someone to dig into the details of how stack and heap allocations work on your system to explain the (undefined) behavior you're seeing? I think you'd need to tell us what operating system and compiler you are using. – David Grayson May 13 '22 at 19:30
  • Related: [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – user4581301 May 13 '22 at 19:53
  • *"the following code should also give a garbage value"* - says *who* ? Not the language standard. You imply some semblance of defined behavior, of which you have none in this case. – WhozCraig May 13 '22 at 20:01

0 Answers0