How & Where memory allocated to unsafe code ? How memory is released in case of unsafe code? RRS feed

  • Question

  • If I have unsafe block in my code where memory is allocated ? (Heap or stack)

    Who is going to allocate memory ? When memory is going to be released ?  How .Net plays role in it?

    Consider following code..

    unsafe { // unsafe context: can use pointers here }

    Example :

    // cs_unsafe_keyword.cs
    // compile with: /unsafe
    using System;
    class UnsafeTest 
       // unsafe method: takes pointer to int:
       unsafe static void SquarePtrParam (int* p) 
          *p *= *p;
       unsafe public static void Main() 
          int i = 5;
          // unsafe method: uses address-of operator (&)
          SquarePtrParam (&i);
          Console.WriteLine (i);

    Tejas Mer

    Friday, February 8, 2013 5:52 AM


All replies

  • you might get some of your answers from this reply

    Mark Answered, if it solves your question and Vote if you found it helpful.
    Rohit Arora

    Friday, February 8, 2013 8:38 AM
  • Nothing actually allocates memory in this example.  The integer (i) is on the stack, and you're just passing the address of that (via a pointer), and using it.

    Basically, you're getting the standard stack allocated when your program starts, and this is going away when the process ends.

    Reed Copsey, Jr. -
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Friday, February 8, 2013 5:03 PM