Skip to content

Instantly share code, notes, and snippets.

@rk76feWF
Last active March 13, 2023 07:05
Show Gist options
  • Save rk76feWF/0b54ed292044bd6834e95c2a38e9e460 to your computer and use it in GitHub Desktop.
Save rk76feWF/0b54ed292044bd6834e95c2a38e9e460 to your computer and use it in GitHub Desktop.
[C言語] 配列の範囲外アクセスを抑制する
#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;
}
@kAwA1290
Copy link

Screenshot 2023-03-13 at 11 14 32

Screenshot 2023-03-13 at 11 14 03

まず、-3をsize_t型にキャストすることにより非常に大きいindexがf関数に与えられるため、f関数はNULLを返す。
これをmain関数内のprintf関数で参照することで、NULLポインタの参照が発生している。
NULLポインタ参照は未定義動作であり実行環境によりその振る舞いは異なるため、segvとなってもおかしくない。

@rk76feWF
Copy link
Author

continue忘れてた。
thank you!
@kAwA1290

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment