How to prove value types are created in stack and ref types on hea

G

Guest

Are there any way to prove that a variable of value type is created in stack
and a variable of ref type are created in heap?

I just take it granted as everybody and every books and pages says so. But
to how to prove it? Are there any way like finding the memory address of the
variable and then by that address to prove that it is in stack or heap?

Just curious to know and not for ridculing anybody...

Thanks,
Narayanan
 
J

Jon Skeet [C# MVP]

Narayanan said:
Are there any way to prove that a variable of value type is created in stack
and a variable of ref type are created in heap?

I just take it granted as everybody and every books and pages says so.

Don't take it for granted, as it's an overgeneralisation. Here's an
example:

class Test
{
int x;
}

class Program
{
static void Main()
{
Test t = new Test();
}
}

Now, where does t.x live? According to the generalisation of "variable
of value type is created in stack" it would live on the stack, right?
But no - it's part of an object on the heap, so it's on the heap
itself.

See http://pobox.com/~skeet/csharp/memory.html for more on this.

As for proving it - cordbg would probably help, if you really, really
want to, but the CLI spec is probably authoritative enough.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top