索引超过 C 数组的末尾 [英] indexing past the end of C arrays

查看:28
本文介绍了索引超过 C 数组的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 C 编写了一个简短的程序,只是为了看看当索引超出数组末尾时会发生什么.

I wrote a short program in C just to see what happens when you index past the end of an array.

我发现它主要产生随机值(我知道它们实际上不是随机的),直到它每次产生 0 的点(在这种情况下超过末尾的 52 个索引).超过这一点的每个值都会导致程序崩溃.为什么是这样?是不是程序分配的内存空间结束了?

I found that it mostly produces random values (I know they are not actually random) up until a point (52 indexes past the end in this case) where it produced 0 every single time. Every value past this point and the program crashes. Why is this? is it the end of the programs allocated memory space?

main()
{
    int ar[4];
    ar[0] = 99;
    ar[1] = 45;
    printf("array: %d, %d   random value: %d", ar[0], ar[1], ar[55]);
}

我还发现,如果我改变这个总是最终为 0 的值(即 ar[55] = 1000),那么程序的返回码就会上升.

I also found that if I alter this value that always ends up being 0 (i.e. ar[55] = 1000) then the return code for the program goes up.

推荐答案

...只是为了看看当你索引超出数组末尾时会发生什么

尝试访问绑定内存,调用未定义行为.任何事情都可能发生,任何事情都可能发生.

Trying to access out of bound memory, invokes undefined behavior. Anything can happen, just anything.

在您的情况下,由于某些原因,最多可从进程访问索引 52 的内存地址,因此它允许访问.超过 52 的索引指向未分配给进程地址空间的内存区域,因此会引发导致段错误的访问冲突.这根本不是确定性的行为,您无法依赖调用 UB 的程序的输出.

In your case, for some reason, the memory address for upto index 52 is accessible from the process, so it allows the access. Index past 52 points to a memory region not allocated to your process address space and thus, raises the access violation leading to segfault. This is not a deterministic behaviour, at all and there's no way you can rely on the output of a program invoking UB.

这篇关于索引超过 C 数组的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆