(gcc returns mem) Re: When is it time for a 1.0 feature freeze?

Bruno Medeiros brunodomedeiros+spam at com.gmail
Mon Sep 4 03:44:18 PDT 2006


Walter Bright wrote:
> Serg Kovrov wrote:
>> Walter, thanks for your kind and comprehensive answer, but I still do 
>> not get this 'malloc/free do not return memory to OS' part.
>>
>> I just tried simplest example with GCC(mingw): I allocated with 'new' 
>> 1Mb string. Then in process explorer (or in FAR's Process list) I can 
>> see my process usage of 'Private bytes' increases equivalently. When 
>> free this string, with 'delete', i see that 'Private bytes' usage 
>> dropped to same level it was before. Isn't this mean that memory 
>> returned to OS?
> 
> Not necessarily. There's a difference between physical memory and 
> virtual memory. The OS will automatically take away from the process any 
> unused physical memory, although the process retains it as virtual 
> memory. If the process explorer watches physical memory, then that's 
> what it's seeing.

I think Serg is right. I don't know what program he used to monitor  the 
mem usage ("process explorer", is that the Windows Task Manager?), but 
my test confirms what he's saying.

I made a small C program that allocs 100Mb and then frees it. I 
monitored it with Windows XP Task Manager process list, looking at the 
fields "Mem Usage" (physical mem) and "VM Size". Compiling with GCC 
(3.2.3), it does free back the memory to the OS (VM Size decreases after 
the free). I tried the program with DMC but the same does not happen: 
the memory is not returned after the free. I don't have visual C 
available right now so I didn't try that one.

After a google search:
http://www.gnu.org/software/libc/manual/html_node/Freeing-after-Malloc.html
"Occasionally, free can actually return memory to the operating system 
and make the process smaller."
Evidently the Windows version of libc also does the same. And seems it's 
smart enough to return the mem not just when the top of the heap is all 
free (what I was expecting) but also with free pages in the middle of 
the heap. (the test program allocs two segments and frees the first only)


---- test program ----
#include <stdio.h>
#include <assert.h>

int main() {
	char buf[80];
	
	char* ptr = (char*) malloc(100000000);
	assert(ptr != NULL);

	char* ptr2 = (char*) malloc(100000000);
	assert(ptr2 != NULL);

	assert(ptr2 > ptr);

	
	printf("Mem Allocated\n"); fflush(stdout);
	gets(buf);
	// Just to see the physical mem usage
	int i;
	for(i = 0; i < 20000; i++)
		ptr[i*4000] = 'X';

	printf("Memory Writen\n"); fflush(stdout);
	gets(buf);

	free(ptr);
	printf("ptr1 free'd\n"); fflush(stdout);

	gets(buf);
}

-- 
Bruno Medeiros - MSc in CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list