What is punning type and what is its purpose? What happens if I use it or don't use it?

Punning type

A form of pointer aliasing where two pointers and both refer to the same location in memory but represent that location as different types. The compiler will treat it as "puns" as unbound pointers. The punning type can cause dependency problems for any data accessible through both pointers.

what is the article trying to say?

+3


source to share


1 answer


That being said, punning is when you have two pointers of different types, both pointing to the same place. Example:

// BAD CODE
uint32_t data;
uint32_t* u32 = &data;
uint16_t* u16 = (uint16_t*)&data; // undefined behavior

      

This code causes undefined behavior in C ++ (and C), since you are not allowed to access the same memory location using incompatible pointers (with a few special exceptions). This is informally called "severe alias violation" because it violates the strict alias rule .



Another way to execute punning function is to concatenate:

// BAD C++ CODE
typedef union
{
  uint32_t u32;
  uint16_t u16 [2];
} my_type;

my_type mt;
mt.u32 = 1;
std::cout << mt.u16[0]; // access union data through another member, undefined behavior

      

This is also undefined behavior in C ++ (but legal in C).

+5


source







All Articles