Skip to content

Latest commit

 

History

History
56 lines (46 loc) · 2.82 KB

File metadata and controls

56 lines (46 loc) · 2.82 KB
title stackalloc (C# Reference)
ms.date 07/20/2015
ms.prod .net
ms.technology
devlang-csharp
ms.topic article
f1_keywords
stackalloc_CSharpKeyword
stackalloc
helpviewer_keywords
stackalloc keyword [C#]
ms.assetid adc04c28-3ed2-4326-807a-7545df92b852
caps.latest.revision 27
author BillWagner
ms.author wiwagn

stackalloc (C# Reference)

The stackalloc keyword is used in an unsafe code context to allocate a block of memory on the stack.

int* block = stackalloc int[100];  

Remarks

The keyword is valid only in local variable initializers. The following code causes compiler errors.

int* block;  
// The following assignment statement causes compiler errors. You  
// can use stackalloc only when declaring and initializing a local   
// variable.  
block = stackalloc int[100];  

Because pointer types are involved, stackalloc requires unsafe context. For more information, see Unsafe Code and Pointers.

stackalloc is like _alloca in the C run-time library.

The following example calculates and displays the first 20 numbers in the Fibonacci sequence. Each number is the sum of the previous two numbers. In the code, a block of memory of sufficient size to contain 20 elements of type int is allocated on the stack, not the heap. The address of the block is stored in the pointer fib. This memory is not subject to garbage collection and therefore does not have to be pinned (by using fixed). The lifetime of the memory block is limited to the lifetime of the method that defines it. You cannot free the memory before the method returns.

Example

[!code-csharpcsrefKeywordsOperator#15]

Security

Unsafe code is less secure than safe alternatives. However, the use of stackalloc automatically enables buffer overrun detection features in the common language runtime (CLR). If a buffer overrun is detected, the process is terminated as quickly as possible to minimize the chance that malicious code is executed.

C# Language Specification

[!INCLUDECSharplangspec]

See Also

C# Reference
C# Programming Guide
C# Keywords
Operator Keywords
Unsafe Code and Pointers