What happens if a user dereferences an uninitialised pointer?

2025

What happens if a user dereferences an uninitialised pointer?

  1. A.

    Compilation error

  2. B.

    You get zero

  3. C.

    It points to a NULL address

  4. D.

    Undefined behavior

Attempted by 146 students.

Show answer & explanation

Correct answer: D

Dereferencing an uninitialized pointer in C/C++ results in undefined behavior. It does not cause compilation errors or guarantee zero values, but rather leads to unpredictable program execution.
NOTE
When a local pointer variable is declared in programming languages like C or C++, it is not automatically set to NULL or given a safe default address. Instead, it contains whatever random data happened to be left over in that memory location (often called a garbage value).

If a program attempts to dereference this uninitialized pointer (i.e., read or write the data at the address it holds), it will try to access a completely arbitrary, random location in memory. This actions triggers what the language standards classify as Undefined Behavior (UB).

What Actually Happens at Runtime?

Because the behavior is undefined, anything could happen depending on your operating system, compiler, and current memory layout:

  1. Segmentation Fault / Crash (Most Common): If the random address falls inside memory owned by the operating system or another process, the OS will immediately terminate your program to protect system security.

  2. Silent Data Corruption: If the random address accidentally points to a valid variable elsewhere inside your own program, you might overwrite critical application data without raising any immediate error.

  3. Apparent Normal Operation: Occasionally, the garbage value might happen to point to a harmless, unused memory block, allowing the program to run fine today but crash unpredictably tomorrow on a different machine.

Explore the full course: Rssb Senior Computer Instructor