0
// C++ program to demonstrate segmentation
// fault when array out of bound is accessed.
#include <iostream>
using namespace std;

int main()
{
    int arr[2];

    // Accessing out of bound
    arr[3] = 10;
    return 0;
}

when i run this code no error is shown in my vscode terimal output

i was expecting a segmentation error message but it shows nothing not even a red cross

in some other cases it shows red cross but no message can some please help! thank you!

  • 3
    ***i was expecting a segmentation error message*** Undefined behavior does not mean that the code will crash. The worst behavior of UB is when the code runs without error and produces the output you expected giving you the false sense that your code was correct. – drescherjm Mar 17 '23 at 16:17
  • *i was expecting a segmentation error message* -- C++ does not work this way. There is no built-in error checking for an out-of-bounds array access. Putting these checks in automatically would slow a C++ program down. You are responsible for ensuring that your array accesses are valid, not C++. – PaulMcKenzie Mar 17 '23 at 16:26
  • 1
    `// C++ program to demonstrate segmentation fault` -- To add , just to spare you any wasted time doing other things like this, there is no guaranteed way to produce any segmentation fault in a C++ program. Nowhere in the C++ langauge does the term "crash", "segmentation fault", etc. exists. When you do wrong things, the behavior is undefined, meaning anything can happen, including crash, work "correctly", work today but not tomorrow, work on your computer but not work on another computer, etc. – PaulMcKenzie Mar 17 '23 at 16:30
  • The checks required to guarantee an error in the event of a mistake like this would slow down ALL programs, including the programs where such errors were demonstrably impossible. C++ follows an ideology of only making a program pay for what it explicitly asks for. If you want buffer overrun checks, you have to write them into the code. – user4581301 Mar 17 '23 at 18:23
  • Also note that because the behaviour is undefined, the writer of the C++ implementation is free to do whatever they want, and this includes building in such checks. You will find that the compiler (and Standard Library implementation) that comes with Visual Studio builds many such checks into debug builds by default. Other compilers often have options to enable additional checking. Eg: https://godbolt.org/z/crerbW8bW tells you that on line 11 the program reached outside the variable defined on line 8. – user4581301 Mar 17 '23 at 18:29

0 Answers0