-fbounds-checkとassert

gccには配列の実行時添字チェックオプション、-fbounds-checkがある。しかし、manによると

  • fbounds-check

For front-ends that support it, generate additional code to check
that indices used to access arrays are within the declared range.
This is currently only supported by the Java and Fortran
front-ends, where this option defaults to true and false respectively.

とのことなので、c/c++には対応していない。

しかも、c++ではnewで動的に確保した配列のサイズを取得する標準的な方法もないようだ(配列の先頭ポインタの前にバイト〜8バイトで配列サイズを入れる場合があるが、それも処理系依存)。

とりあえず、自分でnewしたサイズを覚えておき、assertでチェックするしかない。

assertによる配列サイズチェックのサンプルは以下の通り。

#include <assert.h>
int main(void){
  const int N = 100;
  double *buf = new double[N];
  for(int i=0;i<N+1;i++){
    assert(i<N);
    buf[i] = i;
  }
  delete [] buf;
} 

実行結果はこんな感じ。

$ g++ test.cc
$ ./a.out
Assertion failed: (i<N), function main, file test.cc, line 7.
zsh: abort      ./a.out