0

This is a simple program I wrote to induce segfault

 #include<iostream>
using namespace std;
char* func(){
    char ch='a';
    char *ptr=&ch;
    return ptr;
}
int main()
{
    char *ptr=func();
    cout<<*ptr;
}

As variable ch must've been freed after func() scope ends, I thought that this program would give segmentation fault. But it shows output as 'a'. What am i missing ?

  • 2
    Just because a program gives seemingly correct results is not a guarantee that it's bug free. Your compiler and your operating system may not produce a crash here, but that's not a guarantee that everyone else will get the same results. Or, you may decide to run this program again tomorrow, and it crashes. You never know. – Sam Varshavchik Nov 20 '21 at 23:38
  • 2
    Undefined behavior need not cause a crash. Anything can happen including your program running to its completion and giving you back values you expect. That is the worst behavior of UB. – drescherjm Nov 20 '21 at 23:42
  • 1
    I think that [this answer](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794) from another question explains it very well and provides a great analogy. Maybe that question should also be put into the duplicate list @SamVarshavchik. – Andreas Wenzel Nov 20 '21 at 23:44
  • Thanks for the comments...I understand now that this is undefined behavior. At first I was thinking that this is intended. – Arish Khan Nov 20 '21 at 23:53
  • @ArishKhan *This is a simple program I wrote to induce segfault* -- There is no such thing as a C++ program that absolutely, 100% of the time, across compilers and environments, can guarantee a segfault. The term "seg fault" or "crash" isn't anywhere in the C++ standard document that I know of. What you will find is "undefined behavior", and that means that anything can happen. – PaulMcKenzie Nov 20 '21 at 23:53
  • 1
    A lot of people seem to interpret the term "undefined behaviour" as meaning "the program must crash" or (on unix) "the program must terminate with a segmentation fault". It's nothing of the sort. The standard does not require anything in particular to happen. No visible symptoms is just as correct an outcome of undefined behaviour as an abnormal program termination. A common outcome is code that passes testing by the development team and the program later abnormally terminates when run by the end user. Making for irate end users and bug reports that are difficult to resolve. – Peter Nov 21 '21 at 02:38

0 Answers0