Last Update 2021/06/04
-Wformat-security
フォーマット文字列が文字列リテラルではない場合に警告を出力
テスト概要
-Wformat、-Wformat-securityオプションを使用したコンパイル時の警告出力例
-Wformat-nonliteralと-Wformat-securityを当時に指定した場合の警告出力例
実行環境
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>
int main(void)
{
int n = 1;
char c1[10] = "n = %d\n";
char c2[10] = "test\n";
/* 文字列リテラルではないフォーマット文字列(引数有り) */
printf(c1, n);
/* 文字列リテラルではないフォーマット文字列(引数無し) */
printf(c2);
return 0;
}
-Wformat、-Wformat-securityオプションを使用したコンパイル時の警告出力例
オプション無しで実行
$ gcc sample.c
$ エラー・警告無し
-Wformatオプションのみを指定して実行
$ gcc -Wformat sample.c
$ エラー・警告無し
-Wformatと-Wformat-securityオプションを指定して実行
$ gcc -Wformat -Wformat-security sample.c
sample.c: In function ‘main’:
sample.c:13:9: warning: format not a string literal and no format arguments [-Wformat-security]
printf(c2); 文字列リテラルではないフォーマット文字列(引数無し)
^~
$
-Wformat無しで-Wformat-securityオプションのみを指定して実行
$ gcc -Wformat-security sample.c
cc1: warning: -Wformat-security ignored without -Wformat [-Wformat-security]
$ -Wformat-securityは-Wformatなしでは無視されるとの警告を出力
-Wformat-nonliteralと-Wformat-securityを当時に指定した場合の警告出力例
-Wformat-nonliteralと-Wformat-securityを当時に指定して実行
$ gcc -Wformat -Wformat-nonliteral -Wformat-security sample.c
sample.c: In function ‘main’:
sample.c:10:9: warning: format not a string literal, argument types not checked [-Wformat-nonliteral]
printf(c1, n); 文字列リテラルではないフォーマット文字列が引数を伴う場合は-Wformat-nonliteralによる出力
^~
sample.c:13:9: warning: format not a string literal and no format arguments [-Wformat-security]
printf(c2); 文字列リテラルではないフォーマット文字列の引数が無い場合は-Wformat-securityによる出力
^~
$