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

Like this Article? Subscribe to get every article sent to your email.

Related Post

  • Dispose, Finalize and SuppressFinalizeDispose, Finalize and SuppressFinalize I got the following question recently. What is the difference between Dispose and SupressFinalize in garbage collection?” The problem with this question is it assumes Dispose and […]
  • CSharp fixed keywordCSharp fixed keyword Since I've already mentioned my bias against using unsafe mode in this post: Advanced CSharp - unsafe mode I'll skip my normal rant about that.  Just suffice it to say they don't […]
  • Delegates in .NETDelegates in .NET I received the following question: What is a delegate?  What problem does it solve?  and When might I use a delegate? A delegate is essentially a function pointer.  We have used […]
  • Advanced CSharp – unsafe modeAdvanced CSharp – unsafe mode One of the "advantages" of using CSharp instead of VB.NET is that if programmers want to, they have the option of bypassing the memory management of .NET and working with memory […]
  • Using VB.NET From CSharpUsing VB.NET From CSharp Back when I was teaching .NET to other programmers regularly, I would frequently get the following question from a VB6 programmer moving to CSharp. “Is there any way of using some of the […]

About Dave Bush

Dave Bush is a .NET programmer and Certified ScrumMaster who is passionate about managing risk as it relates to developing software. When he is not writing or speaking about topics related to Application Lifecycle Risk Management (ALRM), he is an example to his peers as he develops web sites in the ASP.NET environment using industry best practices.

One Pingback/Trackback

Awards & Certs