Void Pointers

Void Pointers in C++: Every pointer you have used so far is a labelled parcel. says "there is an integer at this address"; the label tells the compiler how…

The Analogy: An Unlabelled Parcel

Every pointer you have used so far is a labelled parcel. int* p says "there is an integer at this address"; the label tells the compiler how many bytes to read, how to interpret them, and what operations make sense. The label is doing real work.

A void* is the same parcel with the label torn off. The address is still perfectly good — you simply no longer know what is inside. You cannot open it (*p will not compile), you cannot count parcels along the shelf (p + 1 is meaningless without a size), and you certainly cannot ask it how big it is. All you can do is carry it around, compare it, and hand it to somebody who knows what it should be.

That last part is the entire use case. A void* lets you write a function that transports data without caring about its type — which is how C achieved generic code, and why every C callback API in existence takes one. The price is that the knowledge of the real type has moved out of the compiler's hands and into your head, or into a separate tag you have to carry alongside. Get it wrong and the compiler cannot help you: casting a void* back to the wrong type is undefined behaviour that compiles silently.

In C++ you should reach for templates, std::variant or virtual functions instead. void* remains worth understanding because you will meet it at every C boundary, in malloc, in memcpy, in qsort, and in every thread and callback API written before templates existed.


Syntax or Core Structure

#include <iostream>
#include <string>

int main() {
    int count = 42;
    double ratio = 3.5;
    std::string name = "Ada";

    // Any object pointer converts to void* implicitly -- no cast needed
    void* p = &count;
    p = &ratio;
    p = &name;

    // Going back the other way REQUIRES an explicit cast
    p = &count;
    // std::cout << *p;                       // ERROR: cannot dereference void*
    // std::cout << p[0];                     // ERROR: no size, no indexing
    // ++p;                                   // ERROR: no arithmetic

    int* backToInt = static_cast<int*>(p);    // you assert the type here
    std::cout << *backToInt << "\n";          // 42

    // Printing the address itself is one of the few direct uses
    std::cout << "address: " << p << "\n";

    // Comparison works
    void* q = &count;
    std::cout << "same object? " << (p == q ? "yes" : "no") << "\n";

    // The classic trap: nothing checks that the cast is right
    p = &ratio;
    int* wrong = static_cast<int*>(p);        // compiles fine
    std::cout << "garbage: " << *wrong << "\n";   // UNDEFINED BEHAVIOUR

    // nullptr is a valid void*
    void* nothing = nullptr;
    if (nothing == nullptr) {
        std::cout << "points nowhere\n";
    }
}

Note the asymmetry, which is the safety model in one line: *converting to void* is implicit and always safe; converting from it needs an explicit cast and is entirely your responsibility.*


Technical Depth: What You Lose, and What You Get Back

The three things a void* cannot do

Operationint*void*
Dereference *pYesNo — the size is unknown
Index p[i]YesNo — indexing needs a stride
Arithmetic p + 1YesNo — no stride to scale by
Assign from any object pointerNoYes, implicitly
Compare ==, !=YesYes
Hold nullptrYesYes
Print as an addressNeeds a castDirectly

GCC permits void* arithmetic as an extension, treating the stride as 1. Do not rely on it; it is not standard C++. Cast to unsigned char* when you want byte stepping.

Casting back: which cast, and why not reinterpret_cast

int value = 7;
void* p = &value;

int* a = static_cast<int*>(p);        // correct for void* -> T*
int* b = (int*)p;                     // C style: works, says nothing
int* c = reinterpret_cast<int*>(p);   // legal but overkill and misleading

Use static_cast. Round-tripping T* to void* and back with static_cast is explicitly guaranteed to give you the original pointer. reinterpret_cast is for genuinely unrelated types and signals a much stronger claim than you are actually making; reserve it for that.

One thing static_cast will not do is drop const:

const int fixed = 3;
const void* cp = &fixed;
const int* back = static_cast<const int*>(cp);      // fine
// int* bad = static_cast<int*>(cp);                // ERROR -- good

const void* is the right parameter type for a function that only reads, and it is what std::memcmp takes.

Byte-level work: cast to unsigned char*

Since void* has no arithmetic, byte manipulation goes through unsigned char*, whose stride is 1 by definition:

void copyBytes(void* dest, const void* source, std::size_t count) {
    unsigned char* d = static_cast<unsigned char*>(dest);
    const unsigned char* s = static_cast<const unsigned char*>(source);
    for (std::size_t i = 0; i < count; ++i) {
        d[i] = s[i];
    }
}

That is std::memcpy's signature and roughly its body, and it explains why the standard library's memory functions all take void*: they genuinely do not care what the bytes mean.

The C generic-function pattern

Before templates, this was how you wrote code that worked for any type:

#include <cstdlib>

int compareInts(const void* a, const void* b) {
    int left  = *static_cast<const int*>(a);
    int right = *static_cast<const int*>(b);
    return (left > right) - (left < right);
}

int main() {
    int values[5] = {5, 2, 9, 1, 7};
    std::qsort(values, 5, sizeof(int), compareInts);   // sorted
}

qsort takes a void* array, a count, the element size (because it cannot work it out) and a comparator that unpacks the void*s itself. Compare it with the C++ version:

std::sort(values, values + 5);        // that is the whole thing
qsort (void*)std::sort (template)
Type checkedNoFully
Element sizeYou pass itKnown
ComparatorIndirect function call per comparisonInlined
SpeedSlowerTypically much faster
Wrong typeCompiles, then corruptsWill not compile

std::sort is faster because it keeps the type: the comparison inlines instead of jumping through a function pointer.

The callback user_data idiom

Every C API that lets you register a callback gives you one void* to smuggle your own context through. This is the pattern you will genuinely have to write:

struct Counter { int calls = 0; std::string label; };

// A C-compatible callback: fixed signature, context arrives as void*
void onEvent(int code, void* userData) {
    Counter* c = static_cast<Counter*>(userData);      // cast back to what we passed
    ++c->calls;
    std::cout << c->label << " got code " << code << "\n";
}

void registerHandler(void (*fn)(int, void*), void* userData);   // C-style API

int main() {
    Counter c{0, "sensor"};
    registerHandler(onEvent, &c);                     // hand our address across
}

The rule that makes this safe: the code that casts back must be the same code that cast in. If onEvent and the &c at the call site are not maintained together, nothing will warn you when they drift apart.

Why a void* cannot be safely queried

There is no way to ask a void* what it points at. No typeof, no size, no dynamic_cast (that needs a polymorphic class type). If you must carry the type, carry it explicitly:

enum class Kind { Int, Double, Text };

struct Tagged {
    Kind kind;
    void* data;
};

void print(const Tagged& t) {
    switch (t.kind) {
        case Kind::Int:    std::cout << *static_cast<int*>(t.data); break;
        case Kind::Double: std::cout << *static_cast<double*>(t.data); break;
        case Kind::Text:   std::cout << *static_cast<std::string*>(t.data); break;
    }
}

That works, and it is exactly the hand-rolled version of std::variant — which does the same thing with the tag maintained by the compiler and the casts checked:

#include <variant>

std::variant<int, double, std::string> value = 3.5;
if (std::holds_alternative<double>(value)) {
    std::cout << std::get<double>(value);      // throws if you guess wrong
}

Function pointers are not object pointers

void* is for pointers to objects. Converting a function pointer to void* is not portable standard C++ (POSIX requires it to work for dlsym, which is why the practice persists). Use a correctly typed function pointer, or std::function.

What to use instead

void* was forModern C++
Any-type container or algorithmTemplates
One of a known set of typesstd::variant
Any type at all, type-safelystd::any
A callback plus contextstd::function and a lambda capture
Runtime polymorphismA base class with virtual functions
Raw byte buffersstd::byte*, std::span<std::byte>

Every one of those keeps the type information the void* throws away, and every one turns a runtime disaster into a compile-time error.


Real World Example: Wrapping a C-Style Event Callback

This is the situation that will actually put a void* in your code: a C library — a GUI toolkit, a network stack, a device driver — takes a function pointer with a fixed signature plus one void* of your own. You cannot change its signature, so the job is to get your typed C++ object safely across that gap and confine the unsafety to as few lines as possible.

#include <cstddef>
#include <iostream>
#include <string>
#include <vector>

// ---------------------------------------------------------------
// This block is the C library. You do not get to change it.
// ---------------------------------------------------------------
using EventHandler = void (*)(int code, const char* message, void* userData);

struct Subscription {
    EventHandler handler = nullptr;
    void* userData = nullptr;
};

class EventBus {
public:
    void subscribe(EventHandler handler, void* userData) {
        subscribers.push_back(Subscription{handler, userData});
    }

    void publish(int code, const char* message) {
        for (const Subscription& s : subscribers) {
            s.handler(code, message, s.userData);      // context comes back out
        }
    }

private:
    std::vector<Subscription> subscribers;
};

// ---------------------------------------------------------------
// This is our code. Typed, testable, and free of void*.
// ---------------------------------------------------------------
class Logger {
public:
    explicit Logger(std::string name) : label(std::move(name)) {}

    void record(int code, const std::string& message) {
        ++handled;
        if (code >= 500) ++errors;
        std::cout << "[" << label << "] " << code << " " << message << "\n";
    }

    std::size_t handledCount() const { return handled; }
    std::size_t errorCount() const { return errors; }
    const std::string& name() const { return label; }

private:
    std::string label;
    std::size_t handled = 0;
    std::size_t errors = 0;
};

class Counter {
public:
    void bump(int code) {
        ++total;
        if (code >= 500) ++failures;
    }
    std::size_t totalSeen() const { return total; }
    std::size_t failuresSeen() const { return failures; }

private:
    std::size_t total = 0;
    std::size_t failures = 0;
};

// The ONLY two functions in the program that touch void*.
// Each is a two-line shim: cast back, then call a typed method.
void loggerTrampoline(int code, const char* message, void* userData) {
    Logger* logger = static_cast<Logger*>(userData);
    logger->record(code, message ? message : "");
}

void counterTrampoline(int code, const char* /*message*/, void* userData) {
    static_cast<Counter*>(userData)->bump(code);
}

int main() {
    EventBus bus;

    Logger appLog("app");
    Logger auditLog("audit");
    Counter stats;

    // Each subscribe pairs a trampoline with the object it will cast to.
    bus.subscribe(loggerTrampoline, &appLog);
    bus.subscribe(loggerTrampoline, &auditLog);
    bus.subscribe(counterTrampoline, &stats);

    bus.publish(200, "request ok");
    bus.publish(404, "not found");
    bus.publish(500, "database unreachable");
    bus.publish(503, "upstream timeout");

    std::cout << "\n-- totals --\n";
    for (const Logger* log : {&appLog, &auditLog}) {
        std::cout << log->name() << ": " << log->handledCount()
                  << " events, " << log->errorCount() << " errors\n";
    }
    std::cout << "counter: " << stats.totalSeen() << " events, "
              << stats.failuresSeen() << " failures\n";
}

Output:

[app] 200 request ok
[audit] 200 request ok
[app] 404 not found
[audit] 404 not found
[app] 500 database unreachable
[audit] 500 database unreachable
[app] 503 upstream timeout
[audit] 503 upstream timeout

-- totals --
app: 4 events, 2 errors
audit: 4 events, 2 errors
counter: 4 events, 2 failures

The structural point is where the void* lives. Logger and Counter know nothing about it — they have ordinary typed methods, they can be unit-tested with no event bus in sight, and neither contains a cast. All the danger is concentrated in two three-line trampoline functions whose entire job is to restore the type the C API discarded. When something goes wrong with a void*, that is where you look, and there is nowhere else it could be.

Notice that the same loggerTrampoline serves both appLog and auditLog. The function is stateless; the state arrives through userData on every call. That is exactly what the void* buys — one C-compatible function pointer can front any number of distinct objects, which a plain function with captured state could not do. And note that counterTrampoline casts to a completely different class through the same void* slot; the bus stores both in one std::vector<Subscription> without knowing either type.

The invariant that makes it safe is the pairing: bus.subscribe(loggerTrampoline, &appLog) says "when you call this function, hand it that address." The cast inside is correct only because of what the call site passed. Nothing checks it — pass &stats with loggerTrampoline and the code compiles cleanly, then calls Logger::record on a Counter, and the behaviour after that is undefined. Keeping each trampoline immediately adjacent to nothing but its one cast, and naming both after the type they expect, is the discipline that keeps the pairing visible.

Two smaller details are load-bearing. message ? message : "" guards against the C API passing a null const char*, which a C library is entitled to do and which would otherwise construct a std::string from nullptr — undefined behaviour. And the objects (appLog, auditLog, stats) must outlive the subscription: the bus holds bare addresses with no ownership, so if these were locals in a function that returned while the bus lived on, every stored void* would dangle. A void* conveys no lifetime information whatsoever, which is a second thing the type system would ordinarily have helped with.

In pure C++ the whole arrangement collapses to one line, because a lambda can capture the context the void* was smuggling:

std::vector<std::function<void(int, const std::string&)>> subscribers;
subscribers.push_back([&appLog](int code, const std::string& msg) {
    appLog.record(code, msg);
});

No casts, no trampolines, no possible type mismatch. Use that whenever the API is yours. Use the trampoline pattern when it is not.


Common Mistakes

  1. Dereferencing a void*. *p does not compile, and it should not — there is no size to read.
  2. Doing arithmetic on it. p + 1 has no defined stride. Cast to unsigned char* first.
  3. Casting back to the wrong type. It compiles silently and the result is undefined behaviour. This is the bug void* exists to enable.
  4. Using reinterpret_cast for the round trip. static_cast is correct and guaranteed; reinterpret_cast overstates the claim.
  5. Casting away const. If it arrived as const void*, it must go back to const T*.
  6. Passing the address of a temporary or a local that dies first. The callback fires later and the void* dangles.
  7. Assuming you can inspect it. There is no way to ask a void* what it points at. Carry a tag, or use std::variant.
  8. Converting function pointers through void*. Not portable standard C++.
  9. Using void* for genericity in new C++ code. Templates do the same job with full type checking and better speed.
  10. Forgetting the element size at a C boundary. qsort and memcpy need a count in bytes or elements because the void* cannot supply it.

Best Practices

  • Prefer templates, std::variant, std::any or virtual functions. Reach for void* only at a C boundary you do not control.
  • Confine every cast to a thin trampoline function so all the unsafety sits in one reviewable place.
  • Always static_cast, never a C-style cast, when converting back.
  • Use const void* for read-only parameters.
  • Cast to unsigned char* (or std::byte*) for byte work, never rely on void* arithmetic extensions.
  • Keep the pointer and its length together. A void* on its own is half the information.
  • Guarantee the pointee outlives the callback. void* carries no ownership and no lifetime.
  • Name the trampoline after the type it casts to, so a mismatched registration is visible at the call site.
  • Null-check anything a C API hands you before dereferencing it.

Practice Exercises

  1. Store the addresses of an int, a double and a std::string in the same void* variable in turn, casting each back and printing it. Then deliberately cast the double's address to int*, print the result, and explain why the compiler said nothing.
  2. Write void swapBytes(void* a, void* b, std::size_t size) that exchanges size bytes between two addresses by casting to unsigned char*. Test it on two ints and on two doubles with the same function.
  3. Write a Tagged struct holding a Kind enum and a void*, plus a describe function that switches on the tag and casts accordingly. Then rewrite it with std::variant and list the specific mistakes the variant version makes impossible.
  4. Take the trampoline example and add a third subscriber class of your own. Then, in a comment, describe exactly what would happen if you registered it with loggerTrampoline by mistake, and what compiler diagnostic you would get.