10

I have a class which have a static member. As I understand, all static members are common for all instances of the class, which means static members would be allocated memory only once. Where is this memory allocated (Stack or Heap) and when does this memory get allocated?

EDIT: This memory is different from a instance level memory. How does this memory get referenced? Does this memory get allocated at the time of compilation?

johnnyRose
  • 7,310
  • 17
  • 40
  • 61
Vaibhav Jain
  • 33,887
  • 46
  • 110
  • 163
  • 3
    possible duplicate of http://stackoverflow.com/questions/337019/hows-memory-allocated-for-a-static-variable – James Apr 16 '10 at 08:17

3 Answers3

4

Static members are always stored in the global heap, even reference type members. However, this heap is not the normal garbage collected heap. Find out more here: http://www.codeproject.com/KB/cs/codeconcepts.aspx

Simeon
  • 5,519
  • 3
  • 29
  • 51
1

The memory allocation for static members is done just when the type is used for the time, be it as declaration for a variable or access to a static member.

As already stated, memory allocation for static members is done on the heap.

Vaibhav Jain
  • 33,887
  • 46
  • 110
  • 163
Oliver Friedrich
  • 9,018
  • 9
  • 42
  • 48
0

This memory as allocated on heap. Each type has static constructor which performs initialization of the type. It is executed before type is accessed.

Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
  • This memory is different from a instance level memory. How this memory get referenced. and Do this memory get allocated at the time of compilation. – Vaibhav Jain Apr 16 '10 at 08:20