Search code examples
language-agnosticmemory-managementgarbage-collectionmanaged-code

Why don't managed languages offer the ability to manually delete objects?


Lets say you want to write a high performance method which processes a large data set. Why shouldn't developers have the ability to turn on manual memory management instead of being forced to move to C or C++?

void Process()
{
    unmanaged
    {
        Byte[] buffer;
        while (true)
        {
            buffer = new Byte[1024000000];

            // process

            delete buffer;
        } 
    }   
}

Solution

  • Because allowing you to manually delete a memory block while there may still be references to it (and the runtime has no way of knowing that without doing a GC cycle) can produce dangling pointers, and thus break memory safety. GC languages are generally memory-safe by design.

    That said, in C#, in particular, you can do what you want already:

    void Process()
    {
        unsafe
        {
            byte* buffer;
            while (true)
            {
                buffer = Marshal.AllocHGlobal(1024000000);
    
                // process
    
                Marshal.FreeHGlobal(buffer);
            } 
        }   
    }
    

    Note that, as in C/C++, you have full pointer arithmetic for raw pointer types in C# - so buffer[i] or buffer+i are valid expressions.