Hacker News new | ask | show | jobs
by garethrees 2815 days ago
The cast is defined by ISO/IEC 9899:1990 §6.3.2.3.1, since block is a pointer to void, and struct header_t is an object type:

"A pointer to void may be converted to or from a pointer to any incomplete or object type."

The subtraction is defined by §6.5.6.8, provided that block points to an element of a large enough array object:

"When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression."

(There's similar text in other versions of the C standard.)

1 comments

That part of the standard only covers the cast. It means that you won't mangle a pointer if you cast it to a void pointer and then back to the original pointer type.

Accessing the data that is being pointed at is another matter entirely. You must satisfy alignment constraints. You also must not read any memory as a type other than what it was written as, aside from a very limited exception for type char.

There doesn't seem to be any pointer dereference on the line that paavoova quoted, so I don't see how your comment applies.
The trouble is that it is very easy to interpret things the wrong way. You showed that the casting is OK. People will tend to wrongly assume that they are home free at that point, and everything will be standards-compliant. Most people don't realize that the dereference itself can be a problem. Casting is very frequently followed by non-compliant dereferences. The gcc warnings about strict aliasing do not catch all the problems. Adding more casts, including one to a void pointer, is a common way to make warnings go away without actually stopping the compiler from breaking non-compliant code.

Looking at the full code on the web site, I think it is compliant but dangerous. It is decently likely to trigger gcc bugs.