ballpointpenthief wrote On 04/10/06 11:04,:
OK, so you are saying that if this practice was widespread it would be
a bad idea. I shall accept that as true.
I'm still new to C, and programming full stop, and if I could return
some variable from main() instead of a constant while I am working on
one of my programmes, I would feel a lot happier about my ability to
free memory.
Do you agree that this would be good practice and how should I approach
this?
No. You're trying to co-opt a mechanism designed for
one purpose and twist it to an entirely unrelated purpose.
After all, what's special about the amount of un-freed
memory? Why not return the number of un-closed files, or
the maximum function call depth, or the number of strlen()
calls that returned zero? All these and more might be of
interest in some circumstances, and it makes little sense
to try to cram them all through the same needle's eye.
Note, also, that when you return from main() or call
exit() your program is not necessarily finished yet and the
amount of un-freed memory at the moment main() returns may
not be the same as the amount when execution finally ceases.
Here's a simple (and stupid) example:
#include <stdlib.h>
static void gobble(void) {
void *p;
while ((p = malloc(30000)) != NULL)
;
}
int main(void) {
atexit(gobble);
return 0; /* no un-freed memory */
}
.... and its converse:
#include <stdlib.h>
static char *bigarray = NULL;
static void cleanup(void) {
free(bigarray);
}
int main(void) {
atexit(cleanup);
bigarray = malloc(1000);
return (bigarray == NULL) ? 0 : 1000;
}
You may well look at these and say "I would never
do anything so silly," but a more careful look suggests
that the second example really isn't so silly after all.
For example, do you suppose stdin, stdout, and stderr
might own buffer areas they obtained from malloc()? How
about the internal operation of atexit(): might it use
malloc() to get space to store the function pointer?
All of a sudden you find you need to distinguish between
"your" allocated memory and "somebody else's" allocated
memory, and not long after you'll discover that there
are several "somebody elses" in a typical program.
Vigilance in managing memory is a Good Thing, but
this particular idea is not.