-1

As I understand, void * pointers break type safety.

This problem couldn't be solved in plain c?

Lex Ushakov
  • 45
  • 1
  • 9

1 Answers1

0

If "generic data structure" means a data structure that can work with arbitrary data types without the need of adapting the code, then I'd say "No". The reason is that void * is the only data type to which (and from which) a pointer to an arbitrary data type can be safely converted (all other pointer conversions might introduce undefined behaviour due to wrong alignment). Cf, for example, this online C draft standard:

6.3.2.3 Pointers

(1) A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

(7) A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned68) for the referenced type, the behavior is undefined. ...

So unless you reduce the "level of genericity" by allowing only particular sorts of data types (e.g. by capturing them in a common union) or by data structures that manage memory chunks and copy them in and out with memcpy, I'd say void* is the way to go.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • You can use `char*` as a substitute for `void*`, because a `char*` has the weakest alignment requirement of all data types. But it won't be any more typesafe than `void*`, unless you consider explicit casting better than implicit conversions. – Ben Voigt Jun 10 '17 at 23:06
  • @Ben Voigt: technically correct; Yet I'd prefer `void*` over `char*` in this case, because it expresses the semantics "pointer to unknown data type" better. – Stephan Lechner Jun 10 '17 at 23:12
  • Thank you for your answers. But how often in production-ready libraries, for example, cryptography, `void*` pointers are used? And why in this case `c` is preferred over `c++`? – Lex Ushakov Jun 11 '17 at 09:37
  • @Lex Ushakov: actually I cannot say how often they are used; there are use-cases for `void*` in c (probably less than in C++ due to classes and polymorphism); concerning libraries with a strong touch of mathematics, I suppose the primitive data types meet the algorithms right well, so there might be not to much need for dynamic data structures, virtual tables, polymorphism, extensibility with subclassing, ... but that just a guess. – Stephan Lechner Jun 11 '17 at 20:50