Loose-Info.com
Last Update 2021/09/30
TOP - 各種テスト - gcc - 警告関連のオプション - -Wstringop-truncation

-Wstringop-truncation
strncpyなどの数的拘束を伴う文字列操作関数で、文字列操作の際に切り捨てなどが発生する場合に警告を出力
詳細の解説は Using the GNU Compiler Collection を参照

テスト概要

オプション無し、-Wstringop-truncation、-Wallの各オプションを使用した際の警告出力例

実行環境

GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1


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

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

使用ファイル


sample.c
#include <stdio.h> #include <string.h> int main(void) { char sampbuf[10]; strncpy(sampbuf, "12345678", 9); /* コピー元の文字列に終端文字(\0)が含まれない */ strncpy(sampbuf, "123456789", 9); printf("%s\n", sampbuf); return 0; }

動作テスト

オプション無しでコンパイルを実行
$ gcc sample.c エラー・警告無し $

-Wstringop-truncationオプションを指定してコンパイルを実行
$ gcc -Wstringop-truncation sample.c sample.c: In function ‘main’: sample.c:11:2: warning: ‘strncpy’ output truncated before terminating nul copying 9 bytes from a string of the same length [-Wstringop-truncation] strncpy(sampbuf, "123456789", 9); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $ コピー元の文字数と指定したバイト数が同じため、終端文字(\0)が切り捨てが発生する事についての警告

-Wallオプションを指定してコンパイルを実行
$ gcc -Wall sample.c sample.c: In function ‘main’: sample.c:11:2: warning: ‘strncpy’ output truncated before terminating nul copying 9 bytes from a string of the same length [-Wstringop-truncation] strncpy(sampbuf, "123456789", 9); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $ -Wstringop-truncationオプションは-Wallでも有効となる