Home > Articles > Software Development & Management > Object Technology

  • Print
  • + Share This
From the author of Memory Management in Modern Object-Oriented Languages

Memory Management in Modern Object-Oriented Languages

Now, could this same thing happen in Java or .NET? When using Java or .NET, you can almost visualize a firewall between the system resources and the programmer (code). These environments invest a lot in the management and protection of system resources, including memory. C++ relies on programmers to deallocate memory in destructors, whereas Java and .NET use garbage collection.

Let's take a look at the C# code in Listing 3.

Listing 3—C# code attempts to write past the array boundary.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pointers01
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] myArray = new int[5] { 2, 15, 24, 36, 48 };

            Console.WriteLine("myArray[2]=" + myArray[2]);

            myArray[33] = 33;

            Console.WriteLine("myArray[33]=" + myArray[33]);

            Console.WriteLine("Hit Any Key To Continue");

            Console.ReadLine(); //Pause

        }
    }
}

This application is virtually the same as the C++ code in Listing 1. In fact, much of the syntax is similar (since both are descendents of C). However, when this C# application is executed, something totally different happens. Take a look at Figure 5.

Figure 5 C# runtime message.

In this case, the .NET environment detects the fact that the application is stepping outside of its bounds (past the memory allocated to the array), and throws an exception. (The same thing would happen in a similar Java application.) Thus, the program is halted and the debugger kicks in—even indicating the specific line where the offense occurred. Despite the fact that the application technically crashes, no damage is done to outlying memory.

  • + Share This
  • 🔖 Save To Your Account