5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

お姉さんとイケないことシない? - 配列への安全な範囲外アクセス

Posted at

というわけで 備忘録的な話ですが、C# の 配列へのアクセス時に 範囲外のアクセスをすると IndexOutOfRangeException が発生してアクセスできません。

ただ、配列から Span<T> が取れる為、範囲の外にアクセスする方法が無いわけでもないのです。

というのが、今回の趣旨です。

この記事は ReadOnlySpan<T> から Span<T> を取得したり、配列から範囲外を含む Span<T> を取得したりしていますが、それを推奨する記事ではないです。
そういう手段が存在するというのを伝える為の記事です。

やってみる

using System;
using System.Runtime.InteropServices;

int[] array = [1,2,3,4,5];
var span = MemoryMarshal.CreateSpan(ref MemoryMarshal.GetReference(array.AsSpan()), 10);
Console.WriteLine(string.Join(',', span.ToArray()));

sharplab

output
1,2,3,4,5,0,0,0,-39468856,32760

配列の範囲である length:5 以降にもアクセスできてしまっており、 未初期化領域にもアクセスが特にエラーなくできています。

以上。

5
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?