Stackalloc in CSharp

misc_vol4_006 In the last few weeks we’ve looked at several keywords from the csharp language that allow us to deal with memory management directly.  Stackalloc is another keyword from that list.

Before we look at this keyword, we need to review how .NET deals with memory allocation.

In .NET there is a place called the heap and another place called the stack where memory is allocated for our code.  In general, the heap holds all of our objects–things we allocate memory for using the “new” keyword.  The stack holds our value types and pointers to our objects.

Keep in mind the following:

  • Value types include enums and structs
  • If a value type or a pointer is declared as a member of a class than it will be stored in the heap because it fits rule one, not rule two.

As we’ve seen in previous articles, if we want to pass memory to an unmanaged function, we need to lock it.  But there is an alternative way, and that is to use stackalloc.

Stackalloc allows us to allocate memory on the stack from within a method.  By doing this, we can be sure that the memory will not move during the duration of the method call.  To use stackalloc, make sure you are working in an unsafe context.

public unsafe void Foo()
    int* p = stackalloc int[300];
    p[0] = 0;

The advantage to placing the array on the stack instead of the heap is that you no longer have to remember to deallocate the memory like you would have to do if you were allocating on the heap.

Other places talking about stackalloc in csharp:

  • pointers and calculating average in C# – long* pArray = stackalloc long [(int)size]; */ ArrayList pArray = new ArrayList(); // ask for scores for (int i = 0; i < size; i++) { Console.WriteLine(“What is the Score of Test {0}”, (i + 1)); string testScore = Console.ReadLine(); …
  • Speedy C#, Part 3: Understanding Memory References, Pinned Objects … – This includes, interestingly enough, any Array objects you create (such as a byte[[) – they’re reference objects, not value objects. (The one exception is if you use the stackalloc operator in C#). So, suppose I make the following class …
  • Writing C# 2.0 Unsafe Code – Allocating memory on the stack with the stackalloc keyword. C# allows you to allocate on the stack an array of elements of a type which can by pointed to. The stackalloc keyword is used for this, with the following syntax: … NET MVP involved in software development for over 15 years. He is the author of Practical .NET2 and C#2, a .NET book conceived from real world experience with 647 compilable code listings. After graduating in mathematics and computer science, …


Other post in Advanced CSharp

Related Post

One Response to “Stackalloc in CSharp”