How is memory allocated for a static variable?

In the following program:

class Main { static string staticVariable = "Static Variable"; string instanceVariable = "Instance Variable"; public Main(){} } 

instanceVariable will be stored in the memory allocated for the object instance. Where will staticVariable be stored, is it stored in an instance of the object, or somewhere else? If it is stored somewhere else, how are the memory cells connected?

+46
memory-management c #
Dec 03 '08 at 13:01
source share
2 answers

The memory for static variables is usually held in some root (and hidden) object[] . This can be seen by doing! Gcroot on an object in WinDbg (with SOS).

Just to add, these links can never be GC'ed (unless you specify this field), as I recently discovered.

+11
Dec 03 '08 at 13:08
source share

For example, in C ++, staic variables are allocated in the global memory space by global variables. The compiler uses a special naming convention to know that this variable belongs to the class.

0
Dec 03 '08 at 13:12
source share



All Articles