Last Update 2021/08/13
-Wnonnull
nonnull属性が設定されている関数の引数にnullポインタを渡した場合に警告を出力
テスト概要
-Wnonnullオプションを使用したコンパイル時の警告出力例
-Wall、-Wformatの各オプションを使用した場合の-Wnonnullに関する警告出力例
実行環境
GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1
GNU C Library 2.28
GNU Binutils 2.31.1
コード例・出力内容中の表記
・実行例中の太字表記部分は、コマンドなどの入力された文字列を示します。
・「︙」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。
・「︙」や「...」の着色省略表記は、 実際のソースコードや出力内容などを省略加工した部分を示します。
使用ファイル
sample.c
#include <stdio.h>
#include <stdlib.h>
/* nonnull属性を指定して宣言 */
int sampFunc1(char *c) __attribute__((nonnull));
int sampFunc2(char *c);
int sampFunc1(char *c)
{
printf("[1] %s\n", c);
return 0;
}
int sampFunc2(char *c)
{
printf("[2] %s\n", c);
return 0;
}
int main(void)
{
char c[10] = "sample";
char *cptr;
sampFunc1(c);
sampFunc2(c);
/* 引数がnullポインタの場合 */
sampFunc1(NULL);
sampFunc2(NULL);
/* 引数がnullポインタを代入したポインタの場合 */
cptr = NULL;
sampFunc1(cptr);
sampFunc2(cptr);
return 0;
}
-Wnonnullオプションを使用したコンパイル時の警告出力例
オプション無しで実行
$ gcc sample.c エラー・警告無し
$ ./a.out
[1] sample
[2] sample
[1] (null)
[2] (null)
[1] (null)
[2] (null)
$
-Wnonnullオプションを指定して実行
$ gcc -Wnonnull sample.c
sample.c: In function ‘main’:
sample.c:32:2: warning: null argument where non-null required (argument 1) [-Wnonnull]
sampFunc1(NULL); 「non-nullを必要とするところにnullの引数」の警告
^~~~~~~~~
$
-Wall、-Wformatの各オプションを使用した場合の-Wnonnullに関する警告出力例
-Wallオプションを指定して実行
$ gcc -Wall sample.c
sample.c: In function ‘main’:
sample.c:32:2: warning: null argument where non-null required (argument 1) [-Wnonnull]
sampFunc1(NULL); -Wallに-Wnonnullが含まれるため-Wnonnullに関する警告を出力
^~~~~~~~~
$
-Wformatオプションを指定して実行
$ gcc -Wformat sample.c
sample.c: In function ‘main’:
sample.c:32:2: warning: null argument where non-null required (argument 1) [-Wnonnull]
sampFunc1(NULL); -Wformatに-Wnonnullが含まれるため-Wnonnullに関する警告を出力
^~~~~~~~~
$
-Wallと-Wno-nonnullオプションを同時に指定して実行
$ gcc -Wall -Wno-nonnull sample.c エラー・警告無し
$ -Wno-nonnullにより-Wnonnullの警告を無効化