-1

I am writing a simple C# code, wherein I am making use of Pointer to read a value from the memory location. The code works fine when I try to read the value from the same method where I insert the value. However, it does not work when I try to access the value outside of the method.

Here is my code block:

    class Program
    {
        public unsafe static int* numberPointer;
        static void Main(string[] args)
        {
            InsertValueIntoMemoryAddress();
            ReadValueFromMemoryAddress();
        }
        public unsafe static void InsertValueIntoMemoryAddress()
        {
            int number = 100;
            numberPointer = &number;
            Console.WriteLine("The value of Number is {0}", *numberPointer);
            Console.WriteLine("The address of Number is {0}", (int)numberPointer);

            IntPtr ptr = new IntPtr((int)numberPointer);
            int value = Marshal.ReadInt32(ptr);
            Console.WriteLine("Inside the same method --- The value from a Memory location {0}", value);
        }
        public unsafe static void ReadValueFromMemoryAddress()
        {
            IntPtr ptr = new IntPtr((int)numberPointer);
            int value = Marshal.ReadInt32(ptr);
            Console.WriteLine("Outside from the method -- The value from a Memory location {0}", value);
        }
    }

Here is the output of the above program:

The value of Number is 100

The address of Number is 10416820

Inside the same method --- The value from a Memory location 100

Outside from the method -- The value from a Memory location 10416820

Can someone help me why it is not able to read the value from the memory address outside of the method; instead, it just returns the memory address?

  • Note: .net is managed. Addresses are normally not guaranteed to be static over time. Its able to rearrange itself. Although, that might not be the case here. Still a question remains; why use pointers in .net? – Stefan May 21 '19 at 20:22
  • 1
    You would have to [fix](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/fixed-statement) the variable - Do you have a good reason to do that in the 1st place?? – TaW May 21 '19 at 20:31
  • Did you found an answer? – Stefan Dec 27 '19 at 22:06

1 Answers1

0

Due to this:

numberPointer = &number;

The number memory space is on the stack and will be freed after exiting the scope of the method.

Stefan
  • 17,448
  • 11
  • 60
  • 79