gpt4 book ai didi

c# - NULL-Pointer Assignment Partition 是否有错误?

转载 作者:行者123 更新时间:2023-11-28 02:47:45 24 4
gpt4 key购买 nike

从规范我们知道

Each process' virtual address space is split into partitions. On x86 32-Bit Windows, the partition of 0x00000000 - 0x0000FFFF (inclusive) is called NULL-Pointer Assignment Partition. This partition is set aside to help programmers catch NULL-pointer assignments. If a thread in your aprocess attempts to read from or write to a memory address in this partition, an access violoation is raised.

因此,如果我们创建一个具有 64*1024+1 字节字段的假设对象,例如

struct Foo {
byte field1;
byte field2;
...
byte field65536;

byte SomeUnexpectedData;
}* Bar = 0;

Bar->SomeUnexpectedData = 0;

所以这里我们使用了未初始化的空指针,那么环境如何避免呢?我们不能创建大于 64K 的对象还是什么?


C#测试

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace BigObjTest
{
class Program
{
static void Main()
{
var type = GetObjType();
var obj = Activator.CreateInstance(type);
Console.WriteLine(obj);
}

private static Type GetObjType()
{
var typebuilder = GetTypeBuilder();
for (int i = 0; i <= 65535; i++)
{
typebuilder.DefineField("_" + ("b" + i), typeof (byte), FieldAttributes.Private);
}
return typebuilder.CreateType();
}

private static TypeBuilder GetTypeBuilder()
{
const string typeSignature = "MyDynamicType";
var an = new AssemblyName(typeSignature);
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
TypeBuilder tb = moduleBuilder.DefineType(typeSignature
, TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout
, null);
return tb;
}
}
}

奇怪的是,如果对象大于 64K,CLR 会抛出异常,但如果写入 65534 而不是 65535,它将正常工作。所以我猜想,在具有强类型系统的托管语言中这是不可能的。

最佳答案

访问空指针会导致未定义的行为。无法保证系统会检测和/或处理此问题。使用 protected 内存页来捕获大多数错误似乎仍然是一种合理的方法。

您当然可以拥有大于 64kB 的对象。不过,您可能不会在使用它们时发现一些微不足道的错误。

关于c# - NULL-Pointer Assignment Partition 是否有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23848589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com