Hacker News new | ask | show | jobs
by akvadrako 3544 days ago
I am not trying to say it'll work, I'm trying to show that most non-trivial C programs invoke undefined behaviour, according to the spec.

According to my reading an intermediate void pointer allows the pointer casting to stay well defined. However this seems unsafe, even without getting into dereferencing, because implementations are allowed to store omit bits if they assume aligned pointers.

1 comments

I'd say my example demonstrates the spec's statement:

"A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined."

The resulting uint32_t pointer in my example is not correctly aligned for the reference type, so undefined behavior (e.g., a trap on RISC) occurs. What's an example of a statement in a "non-trivial" C program that is in common use but you think is undefined?

Okay, now there are two different topics.

(1) I didn't say your example didn't demonstrate a violation, but it misses the point, because it doesn't invoke an intermediate void pointer:

"A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer."

(2) That was my attempt at coming up with a good example, but it seems, due to the above clause, the casting between incompatible pointers via void * is technically "legal".