为什么一个固定大小的缓冲区(阵列)必须是不安全的? [英] Why is a fixed size buffers (arrays) must be unsafe?

查看:135
本文介绍了为什么一个固定大小的缓冲区(阵列)必须是不安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我想有7个字节(或3或777)值类型。

Let's say I want to have a value type of 7 bytes (or 3 or 777).

我可以将其定义这样的:

I can define it like that:

public struct Buffer71
{
    public byte b0;
    public byte b1;
    public byte b2;
    public byte b3;
    public byte b4;
    public byte b5;
    public byte b6;
}

这是使用固定缓冲更简单的方法来定义

A simpler way to define it is using a fixed buffer

public struct Buffer72
{
    public unsafe fixed byte bs[7];
}

当然,第二个定义更简单。问题在于必须为固定缓冲存储器提供不安全的关键字。据我所知,这是使用指针,因此不安全实施。

Of course the second definition is simpler. The problem lies with the unsafe keyword that must be provided for fixed buffers. I understand that this is implemented using pointers and hence unsafe.

我的问题是它为什么是不安全的?为什么不能C#提供任意常数长数组,并保持它们作为一个值类型,而不是使之成为一个C#引用类型数组或不安全的缓冲区?

My question is why does it have to be unsafe? Why can't C# provide arbitrary constant length arrays and keep them as a value type instead of making it a C# reference type array or unsafe buffers?

推荐答案

由于固定缓冲区是不是一个真正的数组。这是一个自定义的值类型,要生成一个在我所知道的C#语言的唯一途径。没有办法为CLR以验证所述阵列的那索引以安全的方式完成的。在code是无法核实要么。这方面最图形演示:

Because a "fixed buffer" is not a real array. It is a custom value type, about the only way to generate one in the C# language that I know. There is no way for the CLR to verify that indexing of the array is done in a safe way. The code is not verifiable either. The most graphic demonstration of this:

using System;

class Program {
    static unsafe void Main(string[] args) {
        var buf = new Buffer72();
        Console.WriteLine(buf.bs[8]);
        Console.ReadLine();
    }
}
public struct Buffer72 {
    public unsafe fixed byte bs[7];
}

您可以任意访问堆栈帧在这个例子中。标准的缓冲区溢出注射技术将提供给恶意code修补函数的返回地址,并迫使你的code跳转到任意位置。

You can arbitrarily access the stack frame in this example. The standard buffer overflow injection technique would be available to malicious code to patch the function return address and force your code to jump to an arbitrary location.

是的,这是相当不安全的。

Yes, that's quite unsafe.

这篇关于为什么一个固定大小的缓冲区(阵列)必须是不安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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