Re: Doubts about free()
- From: gordonb.9f75g@xxxxxxxxxxx (Gordon Burditt)
- Date: Fri, 31 Oct 2008 07:39:49 -0500
If I have a piece of code something like this
int main()
{
char *s1;
s1= (char *) malloc(sizeof(char) * 200)
while(somecondition)
{
................... //do something
}
free(s1);
while(true)
{
;
} //Infinite loop
}
This is just a sample code, please ignore the syntax errors.
In the above piece of code during execution malloc results in
allocating space physically in the RAM.
In a virtual memory system, it may or may not actually be allocated
physical RAM on allocation, and since you don't use the memory,
it might never be allocated physical RAM.
Now after the first while loop
execution is complete free(s1) is called. At this point of time is
memory returned back to the OS or not always. I guess memory is just
marked as freed for future use by the same process.
It may not be possible to return a chunk of memory as small as 200
bytes to the OS. Memory is likely to be allocated and freed in
larger chunks. If you allocated 200 megabytes, it is more likely
that most of it could be returned.
I have read that in some implementations of OS like some unix flavors
even after free() is executed memory is not released back to the
system. In the above piece of code is it the case that the memory is
never freed up at all in such implementations and remains tied up till
the process dies.
Correct. This is called optimization. It may not be optimal in
all situations.
Assuming there is a need for memory by some other process and no other
free memory is available, is it the case malloc for the other process
would fail under such circumstances. Does the OS do some kind of
tracking and free up this memory.
In a virtual memory system, it is possible that the OS will take
the entire program out of memory (temporarily) to make room for
other programs.
Is there any way to force freeing
up the memory to the system back.
In a UNIX system this operation is often called 'kill'.
.
- Follow-Ups:
- Re: Doubts about free()
- From: Bill Cunningham
- Re: Doubts about free()
- References:
- Doubts about free()
- From: pushpakulkar
- Doubts about free()
- Prev by Date: Re: Trouble with FILE
- Next by Date: Re: Doubts about free()
- Previous by thread: Re: Doubts about free()
- Next by thread: Re: Doubts about free()
- Index(es):
Relevant Pages
|