miBo777
miBo777

Reputation: 35

Segmentation Fault Clarification

Why do A and B result in segmentation fault. Because even though x has not been assigned a value, it technically still has a garbage value right? Also, why is D not a segmentation fault? My answer key says A and B are segmentation fault but that just seems wrong. D should be the one with a segmentation fault because it is trying to return 0. Can someone correct me if I'm wrong.

A.

    int x; 
    int* p = &x;
    cout << p << *p << endl; 

B.

  int* p = new int;
  cout << p << *p <<endl;

C.

  int* p;
  cout << p << *p <<endl;

D.

  int* p = 0;
  cout << p << *p <<endl;

Upvotes: 3

Views: 99

Answers (2)

Employed Russian
Employed Russian

Reputation: 213686

Why do A and B result in segmentation fault.

While both are reading uninitialized value from *p, which is undefined behavior, neither will produce a segmentation fault on any current system.

Both C and D also have undefined behavior, and may produce a segmentation fault on current machines with certain compilers and certain optimization options. A segmentation fault isn't guaranteed, but quite likely here.

This was a question on a practice test that asked, which of these results in a Segmentation Fault. And the answer key said it was A and B.

You must have inverted the meaning of the question (e.g. "which of these does not result in a segmentation fault"), or the answer key is wrong.

Upvotes: 0

Jesper Juhl
Jesper Juhl

Reputation: 31472

"even though x has not been assigned a value, it technically still has a garbage value right?" - Wrong. It has an indeterminate value and reading it is UB.

Reading an uninitialised variable is Undefined Behaviour. You are not allowed to do that, and as a result of doing so, the entire program is invalid and has no meaning. See also https://en.cppreference.com/w/cpp/language/ub

In your examples, A is UB because printing *p reads the value of x which is uninitialised. B is UB because the int pointed to by p is uninitialised. C is UB because p is uninitialised. D is UB because *p dereferences a nullptr.

All your examples are invalid code and the compiler is allowed to generate whatever result it wants and it does not have to tell you that you did anything wrong. It's your responsibility to know all the rules of the language and follow them at all times.

Additional recommended reading material:

What Every C Programmer Should Know About Undefined Behavior #1/3

What Every C Programmer Should Know About Undefined Behavior #2/3

What Every C Programmer Should Know About Undefined Behavior #3/3

Undefined Behavior in 2017

A Guide to Undefined Behavior in C and C++, Part 1

A Guide to Undefined Behavior in C and C++, Part 2

A Guide to Undefined Behavior in C and C++, Part 3

Upvotes: 1

Related Questions