Menu
Coddy logo textTech

NULL Pointers

Part of the Logic & Flow section of Coddy's C journey — lesson 5 of 63.

Sometimes you need to declare a pointer but don't have a valid memory address to assign to it immediately. In these situations, it's important to initialize the pointer to a special value called NULL.

A NULL pointer is a pointer that doesn't point to any valid memory address. In C, NULL is typically defined as 0 or (void*)0. When you initialize a pointer to NULL, you're explicitly stating that it doesn't currently point to anything useful.

int *ptr = NULL;    // Initialize pointer to NULL
printf("%p", ptr);  // This will print 0 or (nil)

Initializing pointers to NULL is considered good programming practice because it prevents your pointer from containing random garbage values. An uninitialized pointer might contain any random memory address, which could lead to unpredictable behavior if you accidentally try to use it.

You can check if a pointer is NULL before using it, which helps prevent crashes and makes your code more robust. This safety check becomes especially important as your programs grow more complex.

challenge icon

Challenge

Easy

Write a C program that demonstrates proper NULL pointer initialization and checking. Your program should:

  1. Declare a pointer to an integer named safe_ptr and initialize it to NULL
  2. Declare a pointer to a character named char_ptr and initialize it to NULL
  3. Check if safe_ptr is NULL using an if statement and print "safe_ptr is NULL" if it is
  4. Check if char_ptr is NULL using an if statement and print "char_ptr is NULL" if it is
  5. Print the memory address stored in safe_ptr using printf with the %p format specifier
  6. Print the memory address stored in char_ptr using printf with the %p format specifier

Your output should display the results in the following format:

safe_ptr is NULL
char_ptr is NULL
safe_ptr address: [address]
char_ptr address: [address]

The actual memory addresses will show as 0, (nil), or similar NULL representation depending on your system, but the format and labels must match exactly as shown above.

Cheat sheet

A NULL pointer is a pointer that doesn't point to any valid memory address. In C, NULL is typically defined as 0 or (void*)0.

Initialize pointers to NULL to prevent random garbage values:

int *ptr = NULL;    // Initialize pointer to NULL
printf("%p", ptr);  // This will print 0 or (nil)

Check if a pointer is NULL before using it to prevent crashes:

if (ptr == NULL) {
    // Safe to handle NULL case
}

Try it yourself

#include <stdio.h>

int main() {
    // TODO: Write your code here
    // Declare and initialize your pointers
    // Check if pointers are NULL
    // Print the required output
    
    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