[Python-Dev] When do sets shrink?

Adal Chiriliuc adal.chiriliuc at gmail.com
Thu Dec 29 02:23:23 CET 2005


I did a little test using MSVC 8.0 on WinXP.

I allocated 128 MB using 128 different buffers of 1 MB each,
freed half of them (alternatively) then freed the remaining half.

I monitored memory usage using the Task Manager and memory is really
freed as indicated by both the "Mem Usage" and "VM Size" process
counters and also by the global "Commit Charge". After exiting the
process the commit charge remains the same, suggesting that all the
memory was indeed released.

Even if the Windows heap documentation says that once memory is
allocated, it won't be released until the heap is destroyed, this
seems to not be true when allocating large chunks. There probably is a
threshold after which VirtualAlloc is used.


#include <windows.h>
#include <stdio.h>
#include <malloc.h>

#define COUNT 128

void main()
{
    char** ptr = malloc(COUNT * sizeof(char*));

    int i;
    for (i = 0; i < COUNT; ++i)
    {
        ptr[i] = malloc(1024 * 1024);
        // Touch memory to really commit it.
        SecureZeroMemory(ptr[i], 1024 * 1024);
    }

    printf("Mem allocated\n");
    Sleep(5000);

    for (i = 0; i < COUNT; i += 2)
        free(ptr[i]);
    printf("Half memory deallocated\n");
    Sleep(10000);

    for (i = 1; i < COUNT; i += 2)
        free(ptr[i]);
    printf("Full memory deallocated\n");
    Sleep(10000);
}



More information about the Python-Dev mailing list