Last active
March 13, 2023 07:05
-
-
Save rk76feWF/0b54ed292044bd6834e95c2a38e9e460 to your computer and use it in GitHub Desktop.
[C言語] 配列の範囲外アクセスを抑制する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
enum | |
{ | |
TABLESIZE = 10 | |
}; | |
static int table[TABLESIZE] = {12, 14, 16, 77, 65}; | |
int *f(size_t index) | |
{ | |
if (index < TABLESIZE) | |
return table + index; | |
return NULL; | |
} | |
int main(void) | |
{ | |
for (int i = -3; i < 5; ++i) | |
{ | |
int *num = f(i); | |
if (num == NULL) | |
{ | |
printf("Error"); | |
continue; | |
} | |
printf("%d ", *num); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
まず、-3をsize_t型にキャストすることにより非常に大きいindexがf関数に与えられるため、f関数はNULLを返す。
これをmain関数内のprintf関数で参照することで、NULLポインタの参照が発生している。
NULLポインタ参照は未定義動作であり実行環境によりその振る舞いは異なるため、segvとなってもおかしくない。