Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I want to know the hexadecimal address of an object on the heap.
Here is the test program (c#) :
C#
namespace ConsoleApp5
{
    internal class Program
    {
        public static int x;
        public static int y;
        static void Main(string[] args)
        {
            x = 2;
            y = 3;
            class1 cls1 = new class1();
        }
    }

    public class class1
    {
        public static int z = 10;
    }
}

In debug mode, I added the following watch variables : (using & to get the memory addresses)
-		&x	0x014c442c	int*
		*&x	2	int
-		&y	0x014c4430	int*
		*&y	3	int
-		&cls1	0x00efee98	ConsoleApp5.class1*
+		*&cls1	{ConsoleApp5.class1}	ConsoleApp5.class1
-		&ConsoleApp5.class1.z	0x014c4434	int*
		*&ConsoleApp5.class1.z	10	int

I get the stack memeory addresses for the int variables and the object pointer, but not for the object itself.

In previous versions of VS it was possible ?

What I have tried:

I couldn't find any adequate information using google, microsoft docs and chatgpt.
Posted
Updated 12-Jun-23 2:58am
v2
Comments
Richard Deeming 12-Jun-23 4:10am    
The obvious question would be why? Unless you pin the object in order to pass its address to an unmanaged function, the GC will freely move it around as it sees fit. Taking its address on the heap at some point in time won't do you much good once that happens.

1 solution

This has nothing to do with VS. It's a .NET thing. Since managed objects can be moved around in memory, the address can change and is thus kind of useless.

The only way to get the address is to tell the Garbage Collector to pin the object in memory. Only then will the address be valid.
C#
string someObject = "Somestring";
GCHandle handle = GCHandle.Alloc(someObject, GCHandleType.Pinned);

Console.WriteLine($"Address: 0x{handle.AddrOfPinnedObject():X}");

handle.Free();
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900