Oracle® Developer Studio 12.5:C 用户指南

退出打印视图

更新时间: 2016 年 7 月
 
 

6.3 使用 lint 进行检查

lint 程序识别与编译器的 -xalias_level 命令同级别的基于类型的别名歧义消除。lint 程序还识别与本章中说明的基于类型的别名歧义消除相关的 pragma。有关 lint -Xalias_level 命令的详细说明,请参见-Xalias_level[=l]

lint 检测并生成警告的四种情况包括:

  • 将标量指针强制转换为 struct 指针

  • 将空指针强制转换为 struct 指针

  • 将结构字段强制转换为标量指针

  • struct 指针强制转换为 -Xalias_level=strict 级别上没有显式别名的 struct 指针

6.3.1 标量指针向结构指针的强制类型转换

在以下示例中,整型指针 p 强制转换为 struct foo 类型的指针。如果 lint -Xalias_level=weak(或更高),此示例将生成错误。

struct foo {
    int a;
    int b;
  };

struct foo *f;
int *p;

void main()
{
    f = (struct foo *)p; /* struct pointer cast of scalar pointer error */
}

6.3.2 空指针向结构指针的强制类型转换

在以下示例中,空指针 vp 强制转换为结构指针。如果 lint -Xalias_level=weak(或更高),此示例将生成警告。

struct foo {
    int a;
    int b;
  };

struct foo *f;
void *vp;

void main()
{
    f = (struct foo *)vp; /* struct pointer cast of void pointer warning */
}

6.3.3 结构字段向结构指针的强制类型转换

在下面的示例中,结构成员 foo.b 的地址被强制转换为结构指针,然后指定给 f2。如果 lint -Xalias_level=weak(或更高),此示例将生成错误。

struct foo{
    int a;
    int b;
  };

struct foo *f1;
struct foo *f2;

void main()
{
    f2 = (struct foo *)&f1->b; /* cast of a scalar pointer to struct pointer error*/
}

6.3.4 需要显式别名

在以下示例中,struct fooa 类型的指针 f1 正在被强制转换为 struct foob。使用 lint -Xalias_level=strict 或更高级别时,这种强制转换需要显式别名,除非 struct 类型是相同的(相同类型的相同数目的字段)。此外,在别名级别 standardstrong 上,假定标记必须匹配才能出现别名。在给 f1 赋值前使用 #pragma aliasstruct fooastruct foob),lint 将停止生成警告。

struct fooa {
    int a;
};

struct foob {
    int b;
};

struct fooa *f1;
struct foob *f2;

void main()
{
    f1 = (struct fooa *)f2; /* explicit aliasing required warning */
}