Adriaan van Os wrote:
Consider the followig test program:
program TestCast; type BytePtr = ^Byte; IntPtr = ^Integer; var theBytePtr : BytePtr; theIntPtr: IntPtr; begin theBytePtr := nil; theIntPtr:= nil; theIntPtr:= IntPtr( theBytePtr); {testcast.pas:11: warning: cast increases required alignment of target type} BytePtr( theIntPtr) := theBytePtr; theBytePtr:= BytePtr( theIntPtr); IntPtr( theBytePtr):= theIntPtr; {testcast.pas:14: warning: cast increases required alignment of target type} end.
- Compiling with gpc produces two warnings as indicated in the
comment. The compiler warns if the "casting" pointer type (outside the parenthesis) points to a larger type than the "casted" pointer type (inside the parenthesis).
Not really. As the message says, it warns that the alignment, not size, of the target type is larger.
Gale Paper brought to my attention that the same holds on the left side of an assignment and I am inclined to regard this as a bug - the compiler should check here for a smaller type, rather than a larger type.
While casting to a smaller type can be dangerous in some cases, so can any pointer conversion, so I'm not convinced that this case deserves particular attention.
OTOH, the alignment problem can be unnoticed if during tests the alignment happens to be big enough or the testing platform doesn't require strict alignment (such as IA32), so here a warning seems justified.
- the -Wcast-align and -Wno-cast-align command-line switches don't
seem to work with gpc.
The attached patch should fix that. But be aware that such code may fail (i.e. segfault or bus error), even after extensive testing, unless you verify and prove that the pointer is in fact properly aligned (in which case it might be preferable to keep it in a variable with proper alignment the whole time and leave the warning on, so the compiler will verify this for you).
Frank