0
0
C++programming~5 mins

Common pointer mistakes in C++

Choose your learning style9 modes available
Introduction

Pointers let you work directly with memory addresses. But if used wrong, they can cause bugs or crashes.

When you want to share data between functions without copying it.
When you need to work with dynamic memory (memory you create while the program runs).
When you want to build complex data structures like linked lists or trees.
When you want to optimize performance by avoiding copying large data.
When you need to interact with low-level system or hardware features.
Syntax
C++
type *pointerName;

// Example:
int *p;

A pointer stores the address of a variable of the specified type.

The asterisk (*) declares a pointer variable.

Examples
Declare a pointer to int and set it to null (no address).
C++
int *p; // pointer to int
p = nullptr; // pointer points to nothing
Pointer p stores the address of variable x.
C++
int x = 10;
int *p = &x; // pointer holds address of x
Trying to use *p without setting p first causes a crash.
C++
int *p;
*p = 5; // ERROR if p is uninitialized
Sample Program

This program shows how to use a pointer correctly and checks before dereferencing to avoid mistakes.

C++
#include <iostream>

int main() {
    int x = 42;
    int *p = &x; // p points to x

    std::cout << "Value of x: " << x << "\n";
    std::cout << "Value via pointer p: " << *p << "\n";

    p = nullptr; // p points to nothing

    // Common mistake: dereferencing nullptr causes crash
    if (p != nullptr) {
        std::cout << *p << "\n";
    } else {
        std::cout << "Pointer p is null, cannot dereference.\n";
    }

    return 0;
}
OutputSuccess
Important Notes

Never use a pointer before assigning it a valid address.

Always check if a pointer is null before dereferencing it.

Be careful with pointers to memory that has been freed or deleted.

Summary

Pointers store addresses and must be initialized before use.

Dereferencing a null or uninitialized pointer causes crashes.

Always check pointers before using them to avoid common mistakes.