4

I'm reading Bjarne Stroustrup C++ FAQ site. Where I saw following line.

  • avoid void* (keep them inside low-level functions and data structures if you really need them and present type safe interfaces, usually templates, to your users)

Why is void* considered unsafe in C++?

msc
  • 33,420
  • 29
  • 119
  • 214
  • 4
    To use `void*` you need at some point to cast it back to whatever type was pointed to originally. If you get that wrong you have undefined behaviour. Put another way `void*` throws away *type safety*. – john Sep 01 '18 at 07:36
  • 3
    Are you familiar with the concept of type safety? – Christian Hackl Sep 01 '18 at 07:47
  • @ChristianHackl Yes, i know. C++ is a strictly typecasting language. then whats problem? – msc Sep 01 '18 at 08:18
  • 2
    @rsp _"strictly typecasting language"_ What do you mean? Shouldn't it be obvious what's the problem with `void*` then? – πάντα ῥεῖ Sep 01 '18 at 08:20
  • @πάνταῥεῖ Please see this link : https://wandbox.org/permlink/DikGnmRJmdUBVlae – msc Sep 01 '18 at 08:24
  • @rsp Sure, and? What makes it _unsafe_ is the fact you need the type cast. If you use the wrong one (e.g. to `double*`), you're lost. It might be hard for a programmer to choose the correct type cast in a more complex scenario. – πάντα ῥεῖ Sep 01 '18 at 08:27

2 Answers2

4

Why is void* considered unsafe in C++?

Because void* represents a memory address without any type information. The compiler cannot know what data type structures are used what the raw memory contains at that address.

In that case the programmer is in charge to do the deciphering of the memory layout themselves correctly, which is an error prone process, and the programmer need to know exactly what they are doing there.

In that sense as it is said what you've been citing (emphasis mine)

  • avoid void* (keep them inside low-level functions and data structures if you really need them and present type safe interfaces, usually templates, to your users)

it is about loosing type safety with void*.


To add up about the cite above:

A template in c++ is preferred, because the original type information won't ever get lost as with generic c style functions using void* as parameter.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

The standard way of providing "generic" functions or data structures in C is to use void* as the data type, so that any allocated memory could be put into it. This has the unfortunate effect of allowing putting different types of data into the same container. In C++, this is solved by providing "templates", which create type-safe instances of functions and classes/structs at compile time, thus ensuring type correctness.