X hits on this document





344 / 396

Chapter ‎18   Unsafe code

then no allocation is made, and the pointer returned is implementation-defined. If there is not enough memory available to allocate a block of the given size, a System.StackOverflowException is thrown.

The content of the newly allocated memory is undefined.

Stack allocation initializers are not permitted in catch or finally blocks (§‎8.10).

There is no way to explicitly free memory allocated using stackalloc. All stack allocated memory blocks created during the execution of a function member are automatically discarded when that function member returns. This corresponds to the alloca function, an extension commonly found in C and C++ implementations.

In the example

using System;

class Test { static string IntToString(int value) { int n = value >= 0? value: -value; unsafe { char* buffer = stackalloc char[16]; char* p = buffer + 16; do { *--p = (char)(n % 10 + '0'); n /= 10; } while (n != 0); if (value < 0) *--p = '-'; return new string(p, 0, (int)(buffer + 16 - p)); } }

static void Main() { Console.WriteLine(IntToString(12345)); Console.WriteLine(IntToString(-999)); } }

a stackalloc initializer is used in the IntToString method to allocate a buffer of 16 characters on the stack. The buffer is automatically discarded when the method returns.

18.8 Dynamic memory allocation

Except for the stackalloc operator, C# provides no predefined constructs for managing non-garbage collected memory. Such services are typically provided by supporting class libraries or imported directly from the underlying operating system. For example, the Memory class below illustrates how the heap functions of an underlying operating system might be accessed from C#:

using System; using System.Runtime.InteropServices;

public unsafe class Memory { // Handle for the process heap. This handle is used in all calls to the // HeapXXX APIs in the methods below.

static int ph = GetProcessHeap();

// Private instance constructor to prevent instantiation.

private Memory() {}

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.331

Document info
Document views557
Page views557
Page last viewedTue Oct 25 05:28:08 UTC 2016