Quote:
> I have a program which continually runs in the background and now is
>leaking a lot of memory. I run memprof and could find that the memory is
>leaked because the memeory allocated to structures is not completely
>freed when I do so.
Since "memprof" is not a part of Standard C, I cannot say much
about it. You would probably get a much better / more-accurate
answer in a group that deals with your specific system, where
the people who read and write articles in that group are familiar
with your system's "memprof". In any case, however:
Quote:
> Below I have replicated the problem I face as simply as possible
(This is a Good Thing, simplifying the problem as much as possible
but not too much :-) )
[some snippage]
Quote:
>typedef struct {
> char *s;
> int d;
> char name[100];
> char desc1[1023];
> char desc2[1023];
> char desc3[1023];
>}dataunit;
If we add these sizes and assume no padding bytes, we get:
sizeof(char *) + sizeof(int) + 100 + 3*1023
or:
sizeof(char *) + sizeof(int) + 3169
which is probably about 3171 through 3179 or so (depending on
sizeof(char *) and sizeof(int)). C does say that sizeof(char)==1.
We might round this to 3180 bytes, a number which seems to pop
up in a moment; or you could just add, somewhere, the call:
printf("sizeof(dataunit) = %lu\n", (unsigned long)sizeof(dataunit));
to find out for sure.
Quote:
>int main(int argc,char* argv){
> dataunit *d;
> d = malloc(sizeof(dataunit));
I prefer the idiom:
d = malloc(sizeof *d);
myself, but this is a style issue.
Quote:
> d->s=(char *) malloc(10240);
It is a bit curious that you cast here, but not in the previous
assignment. You did include <stdlib.h> (in a bit I snipped) so
this is OK.
Note that if both malloc()s work, as is likely, the system will
need to have allocated at least 3180 + 10240 = 13420 bytes.
Apparently "memprof" indicates a larger number:
Quote:
> /* POSITION 1: memory allocated is 16600Bytes */
Next we have:
Quote:
> sleep(5);
Note that sleep() is not a Standard C function. Perhaps it allocates
memory, although the subsequent numbers suggest not.
Quote:
> free(d->s);
This effectively erases the object allocated by the second malloc(),
and therefore should release 10240 bytes for later re-allocation.
16600 - 10240 = 6360, and:
Quote:
> /* POSITION 2: memory allocated is 6360Bytes */
> sleep(5);
> free(d);
This should release another 3180 (assuming my guess at the size is
accurate) bytes. 6360 - 3180 = 3180, and:
Quote:
> /* POSITION 3: memory allocated is 3180Bytes */
So all seems well.
The only unanswered question at this point is: who allocated the
remaining 3180 bytes? It seems particularly odd that this is also,
apparently, sizeof *d. It *could* be a coincidence, of course; it
might just happen that the C library needs 3180 bytes for itself,
independent of "sizeof *d".
--
In-Real-Life: Chris Torek, Wind River Systems (BSD engineering)
Salt Lake City, UT, USA (4039.22'N, 11150.29'W)
(you probably cannot email me -- spam has effectively killed email)