Quote:
> I have a trival question that is confusing me. I am trying to
> determine where/what happens to memory when using calloc() and
> malloc(). It seems that all the requested memory is calloc'd but not
> all is free'd when running this program.
Basically both functions do exactly the same. The only difference is
that "calloc" has a sighlty different prototype and initialises all
bytes to 0.
Quote:
> This is what I am seeing inbetween the gets():
> When list is created (63% mem):
> --------------------------------
> cdaniel 212 12.5 63.6 241564 81520 p0 S 16:09 0:01 ./tmp
> When list is free'd (35% mem):
> -----------------------------
> cdaniel 212 3.5 35.3 132628 45216 p0 S 16:09 0:01 ./tmp
> Where is the memory going? Of course it's gone when the program
> terminates. At least I think :) Any help is appreciated.
> Below is the sample program written specifically to test memory under
> Linux 2.0.12 on a P133 w/128MB.
> #include <stdlib.h>
> #include <stdio.h>
> #include <malloc.h>
> struct temp_struct {
> char dumb[8192];
> struct temp_struct *next;
> };
> struct temp_struct *newp, *hp, *ll = NULL;
> void main(void)
"void main" is not legal C code ! It MUST be "int main".
Quote:
> {
> int i;
> char input[2];
> ll = (struct temp_struct *) calloc(1, sizeof(struct temp_struct));
You should use "malloc()" except for when your *really* need the zero
initialisation. This is only a style and performance issue. It does
not pertain to your problem.
Don't forget to check the value returned by "malloc" for NULL !
Quote:
> hp = ll;
> printf("\r\nPress Enter to create link list...");
> gets(input);
> ll = hp;
> i = 0;
> while(ll) {
> i++;
> ll = hp->next;
> free(hp);
> hp = ll;
> }
> printf("\r\nCalled free() %d times...", i);
> gets(input);
> }
AFAICS your program calls "malloc()" and free once with the correct
arguments.
The answer to your problem is in the FAQ (which you should have read
before posting):
7.25: I have a program which mallocs and later frees a lot of
memory,
but memory usage (as reported by ps) doesn't seem to go back
down.
A: Most implementations of malloc/free do not return freed memory
to the operating system (if there is one), but merely make it
available for future malloc() calls within the same program.
The FAQ has a lot more to offer on the subject of dynamic memory.
Don't hesitate to read it ASAP.
You can get the FAQ at http://www.eskimo.com/~scs/C-faq/top.html or
at ftp://rtfm.mit.edu/pub/usenet/comp.lang.c/C-FAQ-list and it gets
posted to this newsgroup and to news.answers regularly (at the
beginning of each month).
Stephan