数组允许在C中进行越界访问吗? [英] Array allows out of bounds access in C?

查看:38
本文介绍了数组允许在C中进行越界访问吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处是Java/C ++开发人员.尝试学习C,但是我对数组的内存分配感到困惑.

Java / C++ developer here. Trying to learn C but I am confused with memory allocation for arrays.

这是怎么回事?

#include <stdlib.h>
#include <stdio.h>
#include <windows.h>

int main()
{
    int az[3];
    az[2] = 66;
    az[8] = 5214;

    printf("%d\n", az[8]);

    system("pause");
    return 0;
}

输出

5214

那怎么可能?为什么我没有越界异常或程序崩溃?我可以无限做吗?在这种情况下,数组的长度是多少?如果我的数组允许我已经超出范围,那么通过 malloc 分配内存的意义何在?这对我来说是零.

How can that be ? Why do I not get Out of Bounds exception or a program crash? I can I do this infinitely? What is my array's length in this case? What's the point of allocating memory via malloc if my arrays allow me to already put values out of bounds? This makes zero sense to me.

推荐答案

C不执行任何边界检查.使用索引8对长度为3的数组进行索引可能工作正常,可能会巧妙地破坏程序使用的其他内存,或者可能会导致立即分段错误,具体取决于该特定数组在内存中的布局方式.

C does not perform any bounds checking. Indexing an array of length 3 with index 8 may (appear to) work just fine, may subtly corrupt other memory used by your program, or may cause an immediate segmentation fault depending on how that particular array is laid out in memory.

这种类型的错误可以称为缓冲区溢出",是安全漏洞的常见原因,因为在建立索引之前不检查数组的边界可能会导致在运行时对程序进行恶意修改.

This type of error could be called a "buffer overflow" and is a common cause of security vulnerabilities, as not checking the bounds of an array before indexing it can result in malicious modifications to your program at runtime.

欢迎来到疯狂而激动人心的C编码世界!

Welcome to the crazy and exciting world of C coding!

这篇关于数组允许在C中进行越界访问吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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