c++ – How do you know if a pointer can be dereferenced?

Question:

I got some problem: in one part of the program I have a union from a char * pointer and just a char. I would like to display both of these elements (interpreting them differently, of course). But, if a symbol is stored in the union, the pointer cannot be dereferenced – otherwise we will fall. How do you know in advance if dereferencing will lead to a segfault?

Of course, it would be possible to have a special field next to it, in which to store information about what lies in the union. But for this you need to rewrite most of the code, which is hardly suitable, and, for sure, there is a less global solution.

Answer:

It seems to me that there is no absolutely valid, in 100% of cases, a working solution, except for the introduction of some additional flag, which you have already mentioned.

Scroll to Top