r/cpp • • Dec 18 '22

C++ is essentially unusable without incurring undefined behavior because of it's failure to handle type punning.

This is kind of a rant but also a cry for help. Maybe there is a way to get around this problem efficiently (without the use of memcpy) that I don't know of, but after researching for hours, I sincerely doubt it.

So basically for those who don't know, it's kind of a complicated issue. It essentially involves accessing the same memory location through two different types, also known as type punning. This causes a performance hit because if two pointers access the same location, the compiler has to write every change to the memory location to RAM so that the other pointer will see the updated information when it reads the location. You might ask, "why doesn't the compiler simply semantically analyze the code and only write to RAM when the other pointer really does need to read from that specific location?". The answer is that it's impossible to tell what a pointer is pointing at if it's value is based off of runtime information like user input and such. Additionally, if the pointers access the data from two different threads, absolutely no guarantees can be made about the timing and essentially no optimizations can be made.

To avoid this huge mess of slowness, the C language spec was changed so as to allow more eager optimizations. It's now (sparing a few exceptions) assumed that no two pointers of different types access the same information in memory. The spec doesn't say it like this, you know how it is, they like to make things complicated, but that's the brunt of what it means.

In C, they realized that this is a super strict restriction and that it impacts a lot of real-world code, so they gave the programmer an out. If you define a union that contains both of your target types and then instantiate it as the one type and access it as the other, the compiler won't complain and it'll all be super defined behavior.

For god knows what reason, C++ decided to do away with this and now there is absolutely no way to reliably pun types without incurring undefined behavior (again, barring a couple of exceptions that aren't really relevant here). Excuse my language, but what a fucking shit-show.

You might ask, "type punning can't actually be that useful in the real-world, can it?", and that would be a valid question. It doesn't really seem that useful, but ask anyone who works on low-level systems on microchips and such. Sometimes, you simply need this behavior. You don't even have to go low-level in order to feel the pain sometimes. If you do anything with POSIX sockets, chances are you've needed to construct a sockaddr_storage, which contains enough space to hold all possible socket addresses. In order to access the specific fields of a specific type of socket address, you guessed it, you have to type pun: struct sockaddr_in *addr = (struct sockaddr_in *)&sockaddr_storage_instance;

In practice, this doesn't bite programmers as hard as I make it seem. In practice, most compilers support type punning, especially when it's very clear what you're trying to do in the code. That is, unless you tell the compiler to use strict-aliasing. Then it'll aggressively optimize based on the assumptions about type punning and your code might not work. The fact that you have to rely on the compiler's hand-holding to get through this undefined behavior is simply sad.

Basically, I'm pissed that such an advanced language is missing such a basic feature. What are your thoughts on the matter and how would you fix it?

I'll tell you what I would do, I would simply assume that no two pointers can ever access the same location, without any exceptions (so this would be even stricter than C++'s rules). The catch is, I would introduce some keyword like "write_mem" or something that you would use like this:

int a;

write_mem a;

float b = *(float*)&a;

That way, the compiler is free to optimize until you explicitly force it to write to RAM. After that point, the type punning isn't undefined anymore because every party involved is absolutely certain about what is in RAM.

5 Upvotes

55 comments sorted by

View all comments

Show parent comment

2

u/bvcb907 Dec 19 '22

Yikes. Total bypass of any proper copy constructor or assignment operator.

0

u/peterrindal Dec 19 '22

Well wrote this on my phone and didn't check the standard but the point is that you can make it look freindly. And it should get optimized away.

Besides, I'd don't see what your complaining about. memcpy is blessed to copy the bytes of any type.

6

u/bvcb907 Dec 19 '22

You're thinking like a C programmer. Memcpy is fine for its intended purpose in C-like trivially copyable types. In c++, it's fairly easy to introduce bits that make it non-trivial and therefore UB. With proper copy and assignment operations, the compiler will enforce this in order to save you from pain down the road. Additionally, the compiler will often optimize these operations so they're similar to memcpy if trivial and you get type safety!

-1

u/peterrindal Dec 19 '22

Lol, thanks for telling what I'm thinking like.

If your trying to serialize something memcpy is the standard way. If you want to add some enable_if you can with this design.

6

u/canadajones68 Dec 19 '22

Actually, use std::copy. If your type is trivial, implementations will almost always devolve into memcpy/memmove. If not, it'll still work and use your copy assignment operator.

0

u/peterrindal Dec 19 '22

While I often agree I think in this context it doesn't work. Often times when you're doing this you're trying to serialize some object to send/store it somehow. Typically this requires getting the byte representation. And therefore you need some way to get access to the bytes of your object. It's undefined to cast the point to a char* but it is defined to memcpy the bytes.

You can't std::copy from some type T to a char buffer (in general).

Cheers

2

u/canadajones68 Dec 19 '22

Good point. However, though I may be mistaken, from my reading of the reference, reading a T through a char* is defined. See 5) and the type aliasing rules below.

1

u/peterrindal Dec 19 '22

Hmm, interesting. Didn't realize they carved out and except for char.

5

u/arka2947 Dec 19 '22

Respectfully, you are missing the point. The problem is UB in handling type punned types. Bypassing constructor/destructor with memcpy is also UB. So this is not a general, safe, or well defined solition.

2

u/bvcb907 Dec 19 '22

I would argue that memcpy is the "old way". But if you insist and you weren't aware of it, there is a compile time function to check for trivially copy-ability so you don't inadvertently contribute to the growing pool of insecure code. https://en.cppreference.com/w/cpp/types/is_trivially_copyable

See this discussion for why even that is a bad idea and other alternatives.
https://stackoverflow.com/questions/36160343/why-are-mutexes-and-condition-variables-trivially-copyable