#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.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers