Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

stackalloc: practical reference

stackalloc: practical reference: stackalloc reserves a contiguous buffer in the current stack frame, usually as Span<T>.

Version: C# language; verified against C# 14 reference

Syntax

stackalloc /* grammar-specific form */

stackalloc reserves a contiguous buffer in the current stack frame, usually as Span.

Use it for small, short-lived buffers whose size is controlled.

A large size or one derived from untrusted input can overflow the stack.

The memory expires with its scope and, depending on form, may be uninitialized.

The complete program actually uses stackalloc; its exact expected stdout is 3.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

Span<int> values = stackalloc[] { 1, 2, 3 }; Console.WriteLine(values.Length);

Result

3

The complete program actually uses `stackalloc`; its exact expected stdout is `3`.

Sources