Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why dereferencing a null pointer is undefined behaviour?

Tags:

According to ISO C++, dereferencing a null pointer is undefined behaviour. My curiosity is, why? Why standard has decided to declare it undefined behaviour? What is the rationale behind this decision? Compiler dependency? Doesn't seem, because according to C99 standard, as far as I know, it is well defined. Machine dependency? Any ideas?

like image 638
Rajendra Uppal Avatar asked Jul 22 '11 16:07

Rajendra Uppal


People also ask

Is dereferencing a null pointer undefined?

Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.

What could occur if you dereference the null pointer?

A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.

Can we dereference a null pointer in C?

C Language Undefined behavior Dereferencing a null pointer A NULL pointer is guaranteed by the C standard to compare unequal to any pointer to a valid object, and dereferencing it invokes undefined behavior.

WHAT IS null pointer dereference vulnerability?

ABSTRACT Null pointer dereference (NPD) is a widespread vulnerability that occurs whenever an executing program attempts to dereference a null pointer. NPD vulnerability can be exploited by hackers to maliciously crash a process to cause a denial of service or execute an arbitrary code under specific conditions.


1 Answers

Defining consistent behavior for dereferencing a NULL pointer would require the compiler to check for NULL pointers before each dereference on most CPU architectures. This is an unacceptable burden for a language that is designed for speed.

It also only fixes a small part of a larger problem - there are many ways to have an invalid pointer beyond a NULL pointer.

like image 92
Mark Ransom Avatar answered Sep 29 '22 10:09

Mark Ransom