Menu
Coddy logo textTech

Null Pointers

Part of the Logic & Flow section of Coddy's C++ journey — lesson 4 of 56.

When you declare a pointer, it doesn't automatically point to anything meaningful. An uninitialized pointer contains random memory addresses, which can lead to serious errors if you try to use it. This is where null pointers become essential for safe programming.

A null pointer is a pointer that explicitly points to nothing. In modern C++, you create a null pointer by initializing it with nullptr:

int* ptr = nullptr;  // ptr is now a null pointer

The nullptr keyword indicates that the pointer is not pointing to any valid memory location. This is much safer than leaving a pointer uninitialized, because you can check whether a pointer is null before attempting to dereference it.

Before using any pointer, you should verify it's not null using a simple if-statement:

if (ptr != nullptr) {
    // Safe to use *ptr here
    int value = *ptr;
}

This practice prevents your program from crashing due to accessing invalid memory locations. Always initialize pointers to nullptr when you declare them, and check for null before dereferencing.

challenge icon

Challenge

Easy

Create a program that demonstrates safe pointer usage by checking for null pointers before dereferencing them.

The following input will be provided:

  • A string that will be either "valid" or "null"

Your program should:

  1. Declare an integer variable named data and initialize it with the value 42
  2. Declare a pointer named ptr
  3. If the input is "valid", assign the address of data to ptr
  4. If the input is "null", assign nullptr to ptr
  5. Use an if-statement to check if ptr is not null before attempting to use it
  6. If the pointer is not null, print the value it points to
  7. If the pointer is null, print a safety message

Use the following exact output format:

Value: [value]

For null pointers, use this format:

Pointer is null - cannot dereference

Cheat sheet

Initialize pointers to nullptr to avoid undefined behavior:

int* ptr = nullptr;  // ptr is now a null pointer

Always check if a pointer is not null before dereferencing:

if (ptr != nullptr) {
    // Safe to use *ptr here
    int value = *ptr;
}

The nullptr keyword explicitly indicates that the pointer is not pointing to any valid memory location, making your code safer and preventing crashes from accessing invalid memory.

Try it yourself

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Read input
    string input;
    cin >> input;
    
    // Declare the data variable
    int data = 42;
    
    // TODO: Write your code here
    // - Declare a pointer named ptr
    // - Check the input and assign appropriate value to ptr
    // - Use if-statement to safely check and use the pointer
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow