Oracle Solaris Studio 12.2:C++ 用户指南

检查 64 位值的截断

在移植到诸如 V9 的 64 位架构时,数据可能会被截断。截断可能会因赋值(初始化时)或显式强制类型转换而隐式地发生。两个指针的差异在于 typedef ptrdiff_t,它在 32 位模式下是 32 位整型,而在 64 位模式下是 64 位整型。将较长的整型截断为较小的整型会生成警告,如下示例所示。


example% cat test1.c
int x[10];

int diff = &x[10] - &x[5]; //warn

example% CC -c -xarch=v9 -Qoption ccfe -xport64=full test1.c
"test1.c", line 3: Warning: Conversion of 64-bit type value to "int" causes truncation.
1 Warning(s) detected.
example%

可使用 -xport64=implicit 禁用 64 位编译模式下显式强制类型转换导致数据截断时出现截断警告。


example% CC -c -xarch=v9 -Qoption ccfe -xport64=implicit test1.c
"test1.c", line 3: Warning: Conversion of 64-bit type value to "int" causes truncation.
1 Warning(s) detected.
example%

在移植到 64 位架构过程中出现的另一个常见问题是指针的截断。该问题在 C++ 中始终是错误。如果指定 -xport64,导致此类截断的操作(如将指针强制转换为整型)可能会导致在 V9 中出现错误诊断。


example% cat test2.c
char* p;
int main() {
  p =(char*) (((unsigned int)p) & 0xFF); // -xarch=v9 error
  return 0;
}
example% CC -c -xarch=v9 -Qoption ccfe -xport64=full test2.c
"test2.c", line 3: Error: Cannot cast from char* to unsigned.
1 Error(s) detected.
example%