I understand that the free'd memory is not returned to the OS due to some reasons.
What happens to the memory after calling free
is implementation dependent. You tell the operating system that you're done with it. It may or may not release it. One reason for not releasing it is that it can be costly to allocate memory, and if the program asks for more memory the OS can just give back the same memory again.
My question is when I run the program again, instead of reusing the allocated memory, it just keeps on increasing the memory usage of my application.
Nope. As soon as your program terminates all of its allocated memory will be released. Or at least it should. Nevertheless, one could say that "it is not of your business".
I made a simple C program. It doesn't have any error checks, but you can use it to observe the behavior of your program while running it. The code for filling the array with random values and the code for printing it is solely there to make sure that nothing gets optimized away.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int *ptr;
int size;
char c='a';
srand(time(NULL));
while(c!='q')
{
printf("a - allocate memory\n");
printf("f - free memory\n");
printf("p - print array\n");
printf("q - quit\n");
printf("Choose: ");
scanf(" %c", &c);
if(c=='q')
break;
else if(c=='a') {
printf("Size : ");
scanf(" %d", &size);
ptr=malloc(size * sizeof(*ptr));
for(int i=0; i<size; i++)
ptr[i]=rand();
}
else if (c=='f')
free(ptr);
else if(c=='p') {
for(int i=0; i<size; i++)
printf("%d", ptr[i]);
}
}
}
While using it I was watching the process with top -p<PID>
and it looked like this:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
28601 klutt 20 0 4172 692 616 S 0.0 0.0 0:00.00 a.out
When I allocated and freed memory it sometimes showed and sometimes not. It made a difference more frequently if I specified a large size. And yes, I know you specified Windows and I used a Linux command, but I'm pretty sure you can find equivalent tools for analyzing a process in Windows.