Search code examples
c#unsafe

c# why is "unsafe" out of range between Application Address


While studying the pointer through unsafe, I noticed something strange.

unsafe class Program
{


    static unsafe void Main(string[] args)
    {
        int A = 111;
        int B = 222;
        int* C = &A;

        Console.WriteLine("{0} A", (int)&A);
        Console.WriteLine("{0} B", (int)&B);
        Console.WriteLine("{0} *C", (int)*C);
        Console.WriteLine("{0} &C", (int)&C);
        Console.WriteLine("{0} C", (int)C);


        Process proc = Process.GetCurrentProcess();
        IntPtr startOffset = proc.MainModule.BaseAddress;
        IntPtr endOffset = IntPtr.Add(startOffset, proc.MainModule.ModuleMemorySize);

        Console.WriteLine("{0} ~ {1} original", startOffset, endOffset);
        Console.WriteLine("{0}",  (int)endOffset-(int)startOffset);

        long memory = GC.GetTotalMemory(true);
        Console.WriteLine("{0} memory", memory);

    }

}

result
11530536 A
11530532 B
111 *C
11530528 &C
11530536 C
7143424 ~ 7176192 original
32768
33448 memory

1st, why is it outside the start and end addresses of the applications?
I know it's divided into a heap and a stack, but I've added a class, but the results are the same. It's out of range.

2nd, Why is so much memory used?
When I added one int, I found that the amount of memory added is 24. Because all types inherit objects?

Please let me know if there is a problem with the above code.


Solution

  • 1st, why is it outside the start and end addresses of the applications?

    You only show it is out of range for the Main Module. A process can have more modules.
    And I don't think that the stack is inside any module's 'memory range'.

    2nd, Why is so much memory used?

    Why not? It's all virtual.