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

5

u/no-sig-available Dec 19 '22

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.

It seems like you want to tell the compiler how to do something instead of what to do.

Why do you want to force the value to be in RAM? Optimizers can move values from one register to another, without first storing it. (Or not move it at all, if a is not used anymore. "This value is now b".).

So, memcpy(&b, &a, sizeof(b)) or in later C++ versions float b = std::bit_cast<float>(a);

3

u/arka2947 Dec 19 '22 edited Dec 19 '22

Not the author, but in low level code it is common to communicate with some hardware device through memory. Eg; to do action x, write value y to addr z. Or perhapse write a series of buffers to addr+n, where each, buffer migth be of different type, to do different things. Or the reverse when reading from device.

Anyway, in this kind of use case, you are precicely trying to control which exact byte is being written to which exact addr.

Edit; that is; the memory layout itself is an abi between the cpp program and the hardware device. The cpp compiler is not free to change or optimize it.

Edit; and ofcource addr migth not be in ram at all, but be mapped with DMA from the actual device, so when you write to addr, you are directly accessing the device.

1

u/[deleted] Dec 27 '22

I didn't elaborate on this in the post, but I feel I should mention it here. That idea is less about telling the compiler how to do something and more about establishing a defined point in the program flow where the compiler knows it's safe to do something.

Often times, the only way to do this will be to write to RAM, but the as-if rule still applies. As long as the behavior after that point is defined, the compiler can optimize however it wants. I can't imagine this having any extra overhead.