liveBook · Manning

Void pointer

As explained in Modern C

A void pointer is a C pointer value of type void* that can hold the address of an object without retaining its pointed-to type information.

A void pointer, written void*, holds the address of an object without retaining the object’s type information. Any object pointer converts to void* and back; converting back to the same type preserves the pointer value. TAKEAWAY: the conversion removes type information, not the object’s value. section 12.4

Generic storage with malloc

A dynamically allocated vector can use the type-specific pointer only where it matters: double *largeVec = malloc(living * sizeof *largeVec); malloc returns void*, but C converts that object pointer automatically to double*. The sizeof *largeVec expression supplies the size of one double without repeating the type, while malloc itself operates in bytes and knows nothing about the eventual type. Release the storage with free(largeVec) when it is no longer needed. Do not attempt a very large allocation merely to reproduce the example; first compute its required size and assess whether it is feasible. section 13.1

Use void* narrowly and keep these rules visible:

  • Treat void* as a pointer into storage whose original type is temporarily abstracted away. section 12.4
  • Remember that the conversion guarantee applies to object pointers, not function pointers. section 12.4
  • Avoid void* when a more specific pointer type is available; do not declare variables with void alone as their type. section 12.4

How Modern C covers it

How deep it goes
Defines conversion guarantees, storage abstraction, allocation behavior, and avoidance guidance, but does not develop implementation internals.
Examples
Demonstrates a double vector allocated with malloc and sized using sizeof *largeVec.
What it assumes
Assumes pointers and objects, while distinguishing storage, type, value, and object-pointer conversions.
What you can do after
Apply void* through malloc and free while preserving correct object-pointer conversions and allocation sizes.
How it connects
Connects void pointers with object representation, pointers, dynamic allocation, malloc, free, and sizeof.

Also explained in

Compare how 2 books explain void pointer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.