-2

I am getting a segmentation fault in Case 1 and not in Case 2. Can anyone explain to me why's that the case? In case 2, I am just initializing b and not even using it anywhere.

Case 1:

int *a;
*a = 10;

Case 2:

int *a;
int b{};
*a = 200;

I am using g++ (Homebrew GCC 11.3.0_2) 11.3.0

  • Your code has UB (*Undefined Behavior*), so *any* result is valid. Read this: https://en.cppreference.com/w/cpp/language/ub – Jesper Juhl Aug 17 '22 at 08:34
  • 1
    Dereferencing uninitialized pointer is undefined behavior. *"**Undefined behavior** means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB". The program may just crash"* – Jason Aug 17 '22 at 08:39

1 Answers1

1

You are not assigning to a pointer, you are assigning to wherever that pointer is pointing.

Since your pointer is uninitialized it is not pointing at an assignable location, therefore you get a segmentation fault.

Compare this code

int b;
int* a;

a = &b;       // assigning to a pointer
*a = 10;      // now the pointer is pointing somewhere, so this is valid
cout << b;    // print 10

Strictly speaking when you dereference an uninitialized pointer, your program has undefined behaviour, crashing with a segmentation fault and not displaying any error at all, are both possible consequences of undefined behaviour. This is illustrated by your second program, it also has undefined behaviour but it did not get a segmentation fault. This is how C++ works, there is no guarantee that bad programs will crash.

john
  • 85,011
  • 4
  • 57
  • 81
  • Okay, I get that. But what about Case 2? How does another variable initialization effect the outcome? – Aditya Krishna Aug 17 '22 at 08:30
  • @AdityaKG I'll update my answer – john Aug 17 '22 at 08:31
  • @AdityaKG *"Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely on the output of a program that has UB"*. The program may just crash". See [this](https://stackoverflow.com/a/71290415/12002570). – Jason Aug 17 '22 at 08:33