Loose-Info.com
Last Update 2021/08/14
TOP - 各種テスト - gcc - 警告関連のオプション - -Wnonnull-compare

-Wnonnull-compare
nonnull属性が設定されている関数の引数を関数内のnullと比較する場合に警告を出力

テスト概要

その1
-Wnonnull-compareオプションを使用したコンパイル時の警告出力例

その2
-Wallオプションを使用した場合の-Wnonnull-compareに関する警告出力例

実行環境

GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1


コード例・出力内容中の表記

・実行例中の太字表記部分は、コマンドなどの入力された文字列を示します。
・「」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。

使用ファイル


sample.c
#include <stdio.h> /* nonnull属性を指定して宣言 */ int sampFunc1(char *s) __attribute__((nonnull)); int sampFunc2(char *s); int sampFunc1(char *s) { /* nonnull属性を指定した変数をNULLと比較 */ if (s == NULL) { printf("null\n"); } else { printf("%s\n", s); } return 0; } int sampFunc2(char *s) { /* nonnull属性を指定していない変数をNULLと比較 */ if (s == NULL) { printf("null\n"); } else { printf("%s\n", s); } return 0; } int main(void) { sampFunc1("sample"); sampFunc2("sample"); return 0; }

その1

-Wnonnull-compareオプションを使用したコンパイル時の警告出力例

オプション無しで実行
$ gcc sample.c エラー・警告無し $ ./a.out sample sample $

-Wnonnull-compareオプションを指定して実行
$ gcc -Wnonnull-compare sample.c sample.c: In function ‘sampFunc1’: sample.c:10:5: warning: nonnull argument ‘s’ compared to NULL [-Wnonnull-compare] if (s == NULL) 「non-nullの引数sとNULLが比較されている」の警告 ^ $

その2

-Wallオプションを使用した場合の-Wnonnull-compareに関する警告出力例

-Wallオプションを指定して実行
$ gcc -Wall sample.c sample.c: In function ‘sampFunc1’: sample.c:10:5: warning: nonnull argument ‘s’ compared to NULL [-Wnonnull-compare] if (s == NULL) -Wallに-Wnonnull-compareが含まれるため-Wnonnull-compareに関する警告を出力 ^ $

-Wallと-Wno-nonnull-compareオプションを同時に指定して実行
$ gcc -Wall -Wno-nonnull-compare sample.c エラー・警告無し $ -Wno-nonnull-compareにより-Wnonnull-compareの警告を無効化