このコード スニペットを使用します。
// stackoverflow.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char** argv)
{
int i;
int a[10];
// init
a[-1] = -1;
a[11] = 11;
printf(" a[-1]= = %d, a[11] = %d\n", a[-1], a[11]);
printf("I am finished.\n");
return a[-1];
}
コンパイラは Linux x86 用の GCC です。実行時エラーなしで正常に動作します。また、このコードを Valgrind でテストしましたが、メモリ エラーも発生しません。
$ gcc -O0 -g -o stack_overflow stack_overflow.c
$ ./stack_overflow
a[-1]= = -1, a[11] = 11
I am finished.
$ valgrind ./stack_overflow
==3705== Memcheck, a memory error detector
==3705== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3705== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==3705== Command: ./stack_overflow
==3705==
a[-1]= = -1, a[11] = 11
I am finished.
==3705==
==3705== HEAP SUMMARY:
==3705== in use at exit: 0 bytes in 0 blocks
==3705== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==3705==
==3705== All heap blocks were freed -- no leaks are possible
==3705==
==3705== For counts of detected and suppressed errors, rerun with: -v
==3705== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
私の理解では、ヒープとスタックは同じ種類のメモリです。唯一の違いは、それらが反対方向に成長することです。
だから私の質問は:
スタック オーバーフロー/アンダーフローでは発生しないのに、ヒープ オーバーフロー/アンダーフローによってラムタイム エラーが発生するのはなぜですか?
なぜ C 言語設計者は、未定義の動作のままにする以外に、ヒープと同じようにこれを考慮に入れなかったのですか?