Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a segmentation fault from a reference?

Tags:

c++

Suppose the following code:

Foo & foo = getFoo(); foo.attr; // 100% safe access? 

If foo were a pointer, I would check if it is NULL, however because it is a reference, such checking is unecessary. What I want to know is if it is possible to mess up with an object's reference such that it would make accessing its attribute unsafe.

I tried some examples like trying to cast NULL to a Foo object, but I got compile errors. I just want to be sure that the above code is always safe, and that there is no possible inner C++ black magic which I should be aware.

From Benjamin's answer, I could make an example code where I do get a segmentation fault from a reference, thus it answer my question. I'll paste my code just in case someone is interested in the future:

#include <iostream> using namespace std;  class B {     public:     int x;     B() {x = 5;} }; class A {     public:     void f()     {         b = *(B*)NULL;     }     B & getB()     {         return b;     }      B b; };  int main() {     A a;     a.f();      cout << a.getB().x << endl;     return 0; } 
like image 669
Kira Avatar asked Dec 21 '15 18:12

Kira


People also ask

What usually causes a segmentation fault?

Overview. A segmentation fault (aka segfault) is a common condition that causes programs to crash; they are often associated with a file named core . Segfaults are caused by a program trying to read or write an illegal memory location.

Can you catch a segmentation fault?

You can't catch segfaults. Segfaults lead to undefined behavior - period (err, actually segfaults are the result of operations also leading to undefined behavior.

What are three kinds of pointers that can cause a segmentation fault?

Dereferencing or assigning to an uninitialized pointer (wild pointer, which points to a random memory address) Dereferencing or assigning to a freed pointer (dangling pointer, which points to memory that has been freed/deallocated/deleted) A buffer overflow. A stack overflow.


1 Answers

Yes, it's possible.

Foo& Fr = *(Foo*)nullptr; 

Technically, this is already undefined behavior for dereferencing that pointer. But it most likely won't result in any observable error. This probably will though:

Fr.attr = 10; 

However, as Jonathan Wakely points out in the comments, there is no reason for you to check for a case like this. If a function returns an invalid reference, that function is broken, and needs to be fixed. Your usage code is not broken for assuming that the reference is valid. However, a valid reference can become invalid (though not null) in perfectly legitimate code, as mentioned in the answer by David Schwartz. But there is no way for you to check for this. You simply need to know in what cases it can happen, and then stop using the reference.

like image 157
Benjamin Lindley Avatar answered Oct 09 '22 17:10

Benjamin Lindley