Reading history

void Pointer, NULL Pointer, Dangling and Wild Pointers in C

5 min read 1 views

Understand special pointers in C: generic void pointers, NULL checks, dangling pointers after free or return, wild pointers, and safe pointer habits.

Most C crashes and security bugs come from pointers that point somewhere they should not. This lesson covers four special kinds of pointer every C programmer must know: the void pointer that can hold any address, the NULL pointer that deliberately points nowhere, the dangling pointer that points to memory that no longer exists, and the wild pointer that was never initialised. You will learn how each arises and the habits that prevent them.

In this lesson you will learn

  • Using void * for generic code, and casting it back
  • What NULL means and why you must check for it
  • How dangling pointers appear after free or a function return
  • Why uninitialised (wild) pointers are dangerous
  • Safe pointer habits

You should already know pointer basics and malloc and free.

void Pointers, NULL and free

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

static void print_value(const void *data, char type) {
    switch (type) {
        case 'i': printf("int: %d\n", *(const int *)data); break;
        case 'd': printf("double: %.2f\n", *(const double *)data); break;
        case 'c': printf("char: %c\n", *(const char *)data); break;
    }
}

int main(void) {
    int n = 42; double pi = 3.14159; char c = 'Z';
    void *vp = &n;                        /* void* can hold any object address */
    print_value(vp, 'i');
    print_value(&pi, 'd');
    print_value(&c, 'c');
    printf("sizeof(void *) = %zu\n", sizeof(void *));

    int *np = NULL;                       /* points nowhere, on purpose */
    if (np == NULL) printf("np is NULL, not dereferencing it\n");

    int *p = malloc(sizeof *p);
    if (p == NULL) return 1;
    *p = 7;
    printf("before free: %d\n", *p);
    free(p);                              /* p is now dangling */
    p = NULL;                             /* defuse it */
    printf("after free, p is %s\n", p ? "dangling" : "NULL");
    return 0;
}

Output

int: 42
double: 3.14
char: Z
sizeof(void *) = 8
np is NULL, not dereferencing it
before free: 7
after free, p is NULL
  • A void * can store the address of any object. You cannot dereference it directly, because the compiler does not know the size or type of the data; cast it to the right pointer type first, as print_value does.
  • Generic library functions such as malloc, memcpy and qsort use void * so they can work with any type. In C, a void * converts to other object pointer types without a cast, so int *p = malloc(...) is fine.
  • NULL is a pointer value that points to nothing. Functions return it to signal failure, so check before using a result: if (p == NULL). Dereferencing NULL usually crashes with a segmentation fault.
  • After free(p), the memory is returned to the system but p still holds the old address. It is now a dangling pointer. Setting p = NULL straight after freeing makes later mistakes detectable instead of silent.

Returning Addresses Safely

#include <stdio.h>

/* BAD: returns the address of a local variable (dangling after return) */
/* int *bad(void) { int x = 5; return &x; }   -- gcc warns: returns address of local */

/* GOOD: the caller provides the storage */
static void fill(int *out) { *out = 5; }

/* GOOD: static storage lives for the whole program */
static int *counter(void) {
    static int count = 0;
    count++;
    return &count;
}

int main(void) {
    int v;
    fill(&v);
    printf("filled: %d\n", v);
    counter();
    counter();
    printf("counter: %d\n", *counter());

    /* int *wild;  an uninitialised "wild" pointer holds garbage: never use one */
    int *safe = NULL;          /* always initialise pointers */
    printf("safe pointer is %s\n", safe == NULL ? "NULL" : "set");
    return 0;
}

Output

filled: 5
counter: 3
safe pointer is NULL
  • A local variable lives on the stack only while its function runs (see the function call stack). Returning &x from such a function gives the caller a dangling pointer, and GCC warns “function returns address of local variable”.
  • Safe alternatives: let the caller pass in storage (fill), use static storage that lasts for the whole program (counter), or allocate with malloc and document that the caller must free it.
  • A pointer declared without a value holds whatever bits were in that memory: a wild pointer. Always initialise pointers, to a real address or to NULL.

Pointer Problems at a Glance

KindHow it happensPrevention
NULL dereferenceUsing a failed malloc or fopen resultCheck every returned pointer
Dangling (after free)Using memory after freeSet the pointer to NULL after freeing
Dangling (out of scope)Returning the address of a local variableCaller-provided buffer, static or malloc
WildDeclaring int *p; without initialisingAlways initialise pointers
Double freeCalling free twice on the same pointerNULL after free (free(NULL) is harmless)

Common Mistakes

  1. Doing arithmetic on void *; standard C does not allow it (GCC permits it as an extension). Cast to char * for byte offsets.
  2. Assuming freed memory is cleared; it may still contain the old data, which hides bugs during testing.
  3. Keeping two pointers to the same block and freeing through one, leaving the other dangling.
  4. Ignoring compiler warnings; build with -Wall -Wextra and tools such as AddressSanitizer (-fsanitize=address).

Practice Exercises

Exercise 1. Write a generic swap(void *a, void *b, size_t size) that swaps two values of any type.

Show answer
#include <string.h>
void swap(void *a, void *b, size_t size) {
    unsigned char tmp[64];          /* enough for small types */
    if (size > sizeof tmp) return;
    memcpy(tmp, a, size);
    memcpy(a, b, size);
    memcpy(b, tmp, size);
}

Exercise 2. What is wrong with char *name(void) { char buf[20] = "Nadia"; return buf; }, and how would you fix it?

Show answer

buf disappears when the function returns, so the caller gets a dangling pointer. Fix it by returning a string literal (return "Nadia"; with return type const char *), by using static char buf[20], or by letting the caller pass a buffer.

Frequently Asked Questions

Is NULL the same as 0?

In pointer contexts, the constant 0 converts to a null pointer, and NULL is a macro for a null pointer constant. Using NULL makes it clear you mean a pointer. C23 also adds nullptr.

How can I find dangling pointer bugs?

Compile with -fsanitize=address -g (GCC or Clang) or run the program under Valgrind. Both report use-after-free and invalid reads with the exact line numbers.

Summary

  • void * holds any address but must be cast before dereferencing.
  • Check pointers against NULL before use.
  • Set pointers to NULL after free, and never return addresses of local variables.
  • Always initialise pointers to avoid wild pointers.

Next: qsort and bsearch in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *