C++: Avoid Memory Fragmentation

Memory fragmentation means having free memory ("holes") between allocated and in-use memories that can't be used because that slot of memory is too small to fill with data. It is not technically a memory leak, but the memory is technically unusable during run-time.

It is believed C# automatically defrags memory so this would not occur.

Example of memory fragmentation:

for( cnt = 0; cnt < 10000; cnt+=3 )

    // Allocate 30 bytes
    m_memory[ cnt ] = new allocator (30 );
    // Allocate 10 bytes
    m_memory[ cnt + 1 ] = new allocator( 10 );
    // Allocate 110 bytes
    m_memory[ cnt + 2 ] = new allocator( 110 );
   
    // De-allocate 10 bytes
    m_memory[ cnt + 1 ] = null;
    System.gc();
}

The 10 bytes deallocated is stuck between 30 and 110 bytes respectively, and is too small to be reused later on.

---- Memory looks like ----

=================
    OCCUPIED                   30 bytes
    OCCUPIED
=================
    LOST...                        10 bytes
=================
    OCCUPIED                   110 bytes
    OCCUPIED
    OCCUPIED
    OCCUPIED
    OCCUPIED
    OCCUPIED
    OCCUPIED
=================

No comments: