Memory Addresses & Pointers

Memory Addresses & Pointers in C: Every variable in a running program lives at a numbered location, the way every house on a street has a number.

The Analogy: A House Number, Not the House

Every variable in a running program lives at a numbered location, the way every house on a street has a number. A pointer is a slip of paper with a house number written on it.

That single image settles most of the confusion. The slip of paper is small and identical in size no matter how big the house is — which is why a pointer to a char and a pointer to a million-element array are both eight bytes on a 64-bit machine. Reading the slip tells you nothing about the house; you have to go there, and that visit is what *p means.

The analogy also predicts the failure modes. A slip you never wrote on holds a meaningless number, and visiting it is a disaster. A slip that says "no address" — NULL — is honest and safe to check, but visiting it still crashes. And a slip with the number of a house that has since been demolished looks perfectly valid, which is why dangling pointers are the hardest of the three to find.


Syntax or Core Structure

#include <stdio.h>

int main(void) {
    int count = 42;
    int *p = &count;              /* p holds the address of count */

    printf("count     = %d\n", count);
    printf("&count    = %p\n", (void *)&count);
    printf("p         = %p\n", (void *)p);
    printf("*p        = %d\n", *p);

    *p = 99;                      /* write through the pointer */
    printf("count now = %d\n", count);

    printf("sizeof p  = %zu\n", sizeof p);
    printf("sizeof *p = %zu\n", sizeof *p);
    return 0;
}

Output (the two addresses differ on every run, but always match each other):

count     = 42
&count    = 0x7ffd3a1c4b2c
p         = 0x7ffd3a1c4b2c
*p        = 42
count now = 99
sizeof p  = 8
sizeof *p = 4

The line that matters is count now = 99. Nothing assigned to count — the assignment went through p — and that indirection is the entire reason pointers exist. It is how a function reaches out and modifies its caller's variable.

Three symbols, three jobs:

WrittenRead asMeans
int *p;"p is a pointer to int"declares the slip of paper
&count"address of count"produces the house number
*p"the thing p points at"visits the house, to read or to write

The asterisk does double duty — declaration and dereference — which is unfortunate but learnable. In int *p = &count; the star is part of the type; in *p = 99; it is an operation.

The classic demonstration

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(void) {
    int x = 3, y = 8;
    swap(&x, &y);
    printf("x = %d, y = %d\n", x, y);
    return 0;
}

Output:

x = 8, y = 3

C passes everything by value, so swap(x, y) could never work — it would exchange two local copies and return. Passing the addresses by value gives the function the ability to reach the originals. Every time you see & at a call site, that is what it is buying.


Technical Depth: The Three Bad Pointers, and Reading Declarations

A pointer is either usable or it is one of three specific kinds of broken. Knowing which kind you are looking at determines how you debug it.

StateLooks likeWhat happens on *pHow to avoid it
Wild (uninitialised)int *p; then *p = 1;undefined; may write over anythinginitialise to NULL or a real address at declaration
Nullint *p = NULL;reliable crash on most systemscheck if (p != NULL) before use
Danglingpoints at a dead local, or freed memoryoften appears to worknever return &local; set to NULL after free

Of the three, null is the friendly one: it is testable and it fails immediately. The other two are undefined behaviour that can produce a program which passes its tests and corrupts data in production. Initialising every pointer to NULL converts wild pointers into null ones, which is why it is worth doing unconditionally.

Declarations bind the star to the name

int *p, q;        /* p is int*, q is a plain int -- almost never what was meant */
int *p, *q;       /* both pointers */
int *p;
int *q;           /* clearest: one declaration per line */

The asterisk belongs to the declarator, not to the type on the left. This is why int* p, q; — spaced to suggest otherwise — is actively misleading. Declare one pointer per line and the question disappears.

Where const goes changes what is protected

int a = 1, b = 2;

const int *p1 = &a;      /* cannot change *p1;  can point p1 elsewhere */
int *const p2 = &a;      /* can change *p2;     cannot point p2 elsewhere */
const int *const p3 = &a;/* neither */

/* *p1 = 5;   error */
p1 = &b;                 /* fine */
*p2 = 5;                 /* fine */
/* p2 = &b;   error */

Read it right to left: const int * is "pointer to const int", int *const is "const pointer to int". The first is the one you will write constantly, because it is how a function promises not to modify what it was given.

void * is an address with the type forgotten

malloc returns void * and memcpy takes void * because they genuinely do not care what is stored there. You cannot dereference a void * or do arithmetic on it — there is no element size to work with — so it must be assigned to a typed pointer first. In C, unlike C++, no cast is needed for that assignment.

Pointers to pointers

int value = 5;
int *p = &value;
int **pp = &p;

**pp = 7;                /* value is now 7 */

This is not an academic curiosity. It is how a function modifies a caller's pointer rather than the thing it points at — which is exactly what strtol does with its char **end parameter, and what an allocation helper does when it needs to hand a fresh pointer back to its caller.


Real World Example: A Parser That Cannot Lie About Failure

Converting text to a number is the most common place a real program needs pointers, and it is a good illustration because it needs three of them at once: a const char * input it must not modify, an int * out-parameter for the result, and a char ** so strtol can report where it stopped.

The design rule is the one every C API follows: the return value carries success or failure; the out-parameter carries the answer, and is written only on success.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>

/* Returns 0 and writes *out on success.
   Returns -1 and leaves *out untouched on any failure. */
int parse_int(const char *text, int *out) {
    if (text == NULL || out == NULL) return -1;      /* refuse, do not crash */

    errno = 0;
    char *end = NULL;
    long value = strtol(text, &end, 10);             /* &end is a char ** */

    if (end == text)                     return -1;  /* no digits at all */
    if (*end != '\0')                    return -1;  /* trailing junk */
    if (errno == ERANGE)                 return -1;  /* outside long */
    if (value < INT_MIN || value > INT_MAX) return -1;

    *out = (int)value;
    return 0;
}

int main(void) {
    const char *inputs[] = { "42", "-7", "12abc", "", "9999999999" };

    for (size_t i = 0; i < sizeof inputs / sizeof inputs[0]; i++) {
        int value = 0;
        if (parse_int(inputs[i], &value) == 0)
            printf("[%s] -> %d\n", inputs[i], value);
        else
            printf("[%s] -> rejected\n", inputs[i]);
    }
    return 0;
}

Output:

[42] -> 42
[-7] -> -7
[12abc] -> rejected
[] -> rejected
[9999999999] -> rejected

Every rejection is caught by a different check, which is the point of the sequence. "" fails because strtol consumed nothing, so end still equals text. "12abc" parses 12 and leaves end pointing at 'a', so the "did we consume the whole string?" test rejects it — this is the check that atoi lacks entirely, which is why atoi should never be used on input you did not create. And "9999999999" fits in a 64-bit long without setting ERANGE, so it survives that test and is caught only by the explicit INT_MAX comparison. Drop that one line and the function would silently hand back a truncated number.

Notice what the three pointer types each contribute. const char *text promises the caller their string comes back unmodified. int *out lets one function return two things — a status and a value — without a struct. And char **end is strtol writing into our pointer variable, so we can inspect where parsing stopped. The NULL checks at the top cost two comparisons and turn a crash on a caller's mistake into a return code they can handle.


Common Mistakes

  1. Dereferencing an uninitialised pointer. int *p; *p = 5; writes four bytes to an address made of leftover stack bytes. Initialise every pointer at its declaration, to NULL if you have nothing better.
  1. Not checking for NULL before dereferencing. Any pointer that came from a caller, a lookup or an allocation can be null. One if at the top of the function is the whole fix.
  1. int *p, q; — q is an int, not a pointer. The next line that does q = &x then produces a confusing type error. One declaration per line.
  1. Returning the address of a local. int *f(void) { int n = 5; return &n; } hands back a dangling pointer. It frequently prints 5 anyway on the first call, which is what makes it dangerous.
  1. Forgetting & with scanf. scanf("%d", n) passes the value of n as an address. It compiles with a warning under -Wall and corrupts memory at run time.
  1. Confusing *p += 1 with p += 1. The first adds one to the pointed-at value; the second moves the pointer to the next element. And *p++ moves the pointer, returning the old target, because postfix ++ binds tighter than *.
  1. Printing a pointer without casting to void *. printf("%p", p) is undefined for a non-void *; write (void *)p. It usually works, which is exactly why it stays in the code.
  1. Assuming a non-null pointer is valid. Null-ness and validity are different questions. A pointer to a freed block or a dead local is non-null and unusable, and no check can detect it — only discipline about lifetimes can.

Best Practices

  • Initialise every pointer where you declare it, and set it back to NULL the moment the thing it points at goes away.
  • Validate pointer parameters at the top of any function that could be called with a bad one, and return an error rather than crashing.
  • Use const char * and const int * for anything the function only reads. It documents intent and the compiler enforces it for free.
  • Declare one pointer per line so the binding of the asterisk is never in question.
  • Follow the standard-library convention: return a status, write results through out-parameters, and leave out-parameters untouched on failure.
  • Pass a length or capacity next to every pointer that refers to more than one object. The pointer alone never carries that information.
  • Say in a comment who owns what a pointer refers to and who is responsible for releasing it. Ownership is not expressible in C's type system, so it has to live in the documentation.
  • Build with -Wall -Wextra -fsanitize=address,undefined -g while developing. Wild and dangling pointers are precisely what those sanitisers exist to catch.

Practice Exercises

  1. Confirm the model. Declare an int, a double and a char, take a pointer to each, and print for all three: the address, the value through the pointer, sizeof the pointer and sizeof the pointed-at type. Explain why one column is identical across all three rows and the other is not.
  1. Reach back through a parameter. Write void stats(const int *a, size_t n, int *out_min, int *out_max) that computes both extremes in a single pass and tolerates either out-parameter being NULL. Call it three times — with both pointers, with only out_max, and with both NULL — and confirm none of the three crashes.
  1. Meet all three broken pointers. Write one small program per case: a wild pointer, a null dereference, and a dangling pointer returned from a function. Build each normally and record what happens, then rebuild with -fsanitize=address,undefined -g and record what the sanitiser says. Note which case gave the least informative output without the sanitiser.
  1. Extend the parser. Add int parse_range(const char *text, int *out_lo, int *out_hi) that accepts input like "10-25", rejects "25-10", "10-" and "abc", and writes nothing on failure. Use strtol twice with its end pointer to walk the string rather than copying substrings out, and print a table of six inputs with their outcomes.