Loose-Info.com
Last Update 2021/10/25
TOP - 各種テスト - gcc - 警告関連のオプション - -Wsizeof-pointer-div

-Wsizeof-pointer-div
ポインタのサイズを要素のサイズで割る、2つのsizeof式の除算に対する誤りを予想する警告

テスト概要

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

実行環境

GCC-8.2.0
GNU C Library 2.28
GNU Binutils 2.31.1


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

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

使用ファイル


sample.c
#include <stdio.h> int main(void) { int n[10] = {1, 2, 3}; int *p = n; printf("%ld %ld %ld\n", sizeof(n), sizeof(p), sizeof(p[0])); /* nは配列(配列サイズの計算) */ printf("%ld\n", sizeof(n)/sizeof(p[0])); /* pはポインタ(配列サイズの計算としては誤り) */ printf("%ld\n", sizeof(p)/sizeof(p[0])); return 0; }

動作テスト

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

-Wsizeof-pointer-divオプションを指定してコンパイルを実行
$ gcc -Wsizeof-pointer-div sample.c sample.c: In function ‘main’: sample.c:14:27: warning: division ‘sizeof (int *) / sizeof (int)’ does not compute the number of array elements [-Wsizeof-pointer-div] printf("%ld\n", sizeof(p)/sizeof(p[0])); ^ sample.c:6:7: note: first ‘sizeof’ operand was declared here int *p = n; ^ $ 対象のsizeofの除算では配列の要素数が計算されない事への警告

-Wallオプションを指定してコンパイルを実行
$ gcc -Wall sample.c sample.c: In function ‘main’: sample.c:14:27: warning: division ‘sizeof (int *) / sizeof (int)’ does not compute the number of array elements [-Wsizeof-pointer-div] printf("%ld\n", sizeof(p)/sizeof(p[0])); ^ sample.c:6:7: note: first ‘sizeof’ operand was declared here int *p = n; ^ $ -Wsizeof-pointer-divオプションは-Wallでも有効となる