#189 – Memory Management for Stack-Based Objects

When an object is created on the stack, memory is allocated from the stack for that object.

Memory for an object allocated from the stack is not deallocated until the function containing the declaration exits.

        static void Main(string[] args)
        {
            int x = 42;

            SomeMethod();

            // x deallocated when Main() exits
        }

        static void SomeMethod()
        {
            int y = 100;
            int z = 12;
            int sum = y + z;

            // y, z, sum all deallocated when SomeMethod() exits
        }

In practice, you don’t care much when memory for an object is deallocated.  Instead, you care more about the block of code within which you can refer to and use the variable–its scope.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #189 – Memory Management for Stack-Based Objects

  1. kai zhou says:

    Thank you Sean.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: