Find all variables that point to the same memory in Visual Studio

拈花ヽ惹草 提交于 2021-02-11 14:25:12

问题


In Visual Studio 2008, is there a way of finding all the variables that point to the same object as another variable?

So in the example below I would want to find out that ref1 and ref2 both point to the same object as original.

var original = new List<string>() { "Some Data" };
var ref1 = original;
var ref2 = ref1;

Essentially I want to be able to call ReferenceEquals() on all the variables in memory and then see all the ones that are equal. Except I want to be able to do this in the VS2008 IDE.


回答1:


Sounds like you could benefit from a memory profiler. I would recommend Red-Gates:

http://www.red-gate.com/products/ants_memory_profiler/index_v2.htm




回答2:


You can do it by using the SOS Debugging extension's !DumpStackObjects command. (I am using WinDbg but you can also load the extension into VS from the Immediate window)

This command will dump all the stack objects in the following format:

RSP/REG          Object           Name
000000000028ef70 0000000002823a98 System.Collections.Generic.List`1[[System.String, mscorlib]]
000000000028efa0 0000000002823a98 System.Collections.Generic.List`1[[System.String, mscorlib]]
000000000028efa8 0000000002823a68 System.String
000000000028efb0 0000000002823a68 System.String
000000000028efc0 0000000002823a98 System.Collections.Generic.List`1[[System.String, mscorlib]]
000000000028efc8 0000000002823a98 System.Collections.Generic.List`1[[System.String, mscorlib]]
000000000028efd0 0000000002823a98 System.Collections.Generic.List`1[[System.String, mscorlib]]
000000000028efd8 0000000002823a98 System.Collections.Generic.List`1[[System.String, mscorlib]]
000000000028efe0 0000000002823a98 System.Collections.Generic.List`1[[System.String, mscorlib]]
000000000028f000 0000000002823a48 System.Object[]    (System.String[])
000000000028f188 0000000002823a48 System.Object[]    (System.String[])
000000000028f370 0000000002823a48 System.Object[]    (System.String[])
000000000028f398 0000000002823a48 System.Object[]    (System.String[])

In this example you can see that 7 stack locations are pointing to the same object reference.




回答3:


I just found a way of achieving what I wanted, and its all baked into VS2008.

If you hover over a variable while you're debugging, right click on the tooltip and select 'Make Object ID'

This gives that object an id (#1) that appears in the tooltip. So if you've got another variable that points to the same object it will have the same id (#1).



来源:https://stackoverflow.com/questions/1624975/find-all-variables-that-point-to-the-same-memory-in-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!