I am writing a server component on 32 bit Windows (Windows XP). I've lots of allocations, de-allocations and re-allocations in the code. I kept this component running for hours then brought it down. I found lot of memory (Private Bytes) was still allocated to the process (I use SysInternals Process Explorer to monitor private bytes)
Definitely there were no memory leaks in the code. So I investigated further and came up with this piece of code that reproduces exact same behavior.
#define NUMBER_OF_POINTERS 1000
int _tmain(int argc, _TCHAR* argv[])
{
char* ptr[NUMBER_OF_POINTERS] = {} ;
int len[NUMBER_OF_POINTERS]={};
printf("\nCheck private bytes now and press a key to go on realloc");
_getch();
printf("\nRandomly allocating/reallocating memory. Press x to stop...");
while(1)
{
int random_kilobytes = rand() % 7 + 1;
int randomindex = rand()%NUMBER_OF_POINTERS;
int size2increase = random_kilobytes*1024;
assert (len[randomindex]+size2increase > 0);
char* reallocated = (char*) realloc(ptr[randomindex], len[randomindex]+size2increase);
if (reallocated)
{
ptr[randomindex] = reallocated;
len[randomindex] += size2increase;
}
if ((_kbhit()) && (_getch()=='x'))
break;
}
printf("\nPress a key to free allocations");
_getch();
for (int i=0; i<NUMBER_OF_POINTERS; i++)
free(ptr[i]);
int _heapmin_ret = _heapmin();
printf("\n_heapmin returned %d", _heapmin_ret);
printf("\nCheck private bytes now and press a key to exit");
_getch();
return 0;
}
In this code I go on allocating and reallocating memory chunks of increasing size to set of pointers. My findings is:
Memory hold in the form of private bytes at the end of process, is directly proportional to the number of pointers and number of allocations re-allocations made to it.
Details:
If we have many number of
NUMBER_OF_POINTERS
(e.g. 1000) and we allow this code to run till it goes beyond 1 GB and then if wefree
allocations, we'll find lot of Private Bytes still allocated (ranging from 15 MB to 40 MB)If we have very few
NUMBER_OF_POINTERS
(e.g. 1) and and we allow this code to run till it goes beyond 1 GB (May be we need to increasesize2increase
to make it faster) and then if wefree
allocations, we'll find very few Private Bytes still allocated (few kilobytes)
Any explanation to this behavior?