17 October 2023

Global variable stored in stack or heap

Global variable stored in stack or heap

In C#, global variables, which are declared outside of any method, constructor, or block, are stored in the heap memory, not the stack memory. When you declare a global variable, it's allocated on the managed heap, which is a region of the computer's memory managed by the .NET runtime. 

Here's a brief explanation of how global variables are stored:

1. Value Types vs. Reference Types:

   - **Value Types:** If a global variable is of a value type (e.g., `int`, `char`, `bool`), its value is directly stored where the variable is declared. Value types are stored in the stack memory when they are local variables inside methods or in the memory occupied by the object that contains them when they are part of a class or struct. However, global value types are stored on the heap.

   - **Reference Types:** If a global variable is of a reference type (e.g., class instances), the variable itself is stored on the stack as a reference (memory address) pointing to the actual object on the heap.

2. Global Variables and Memory Management:

   - When you declare a global variable of a reference type, the reference to the object is stored in the global variable on the heap. The object itself is allocated on the managed heap.

   - The memory for these global variables and the objects they point to is managed by the .NET garbage collector, which automatically reclaims memory occupied by objects that are no longer in use, preventing memory leaks.

Here's an example to illustrate this:

csharp

public class GlobalExample

{

    // Global reference type variable

    public static MyClass globalObject;

    public static void Main()

    {

        // The globalObject variable is stored on the stack (as a reference)

        // When assigned an object, that object is allocated on the heap

        globalObject = new MyClass();        

        // Rest of the program

    }

}

public class MyClass

{

    // Class definition

}

```

In this example, `globalObject` is a global reference type variable. Its memory is allocated on the stack (as a reference), and the object it points to (`new MyClass()`) is allocated on the heap.

No comments:

Post a Comment

Comments Welcome

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...