On Thu, Jan 03, 2002 at 05:01:50AM -0800, Eric G. Miller wrote: | On Thu, 3 Jan 2002 07:22:59 -0500, dman <[EMAIL PROTECTED]> wrote: | | > On Thu, Jan 03, 2002 at 12:19:25AM -0500, William T Wilson wrote: | > | On Wed, 2 Jan 2002, Richard Cobbe wrote: | > | | > | > I'll agree that the two are related; in fact, I'd go so far as to say | > | > that if a language supports dynamic memory allocation and type-safety, | > | > it *has* to have some sort of automatic storage management system. | > | | > | I don't think that necessarily follows; a manual mechanism for freeing | > | resources would then just set the reference to a NULL value. | > | > Erm, no. The function can't change the environment of its caller : | > | > int main() | > { | > int* ptr ; | > | > /* allocate some space */ | > ptr = malloc( 2*sizeof(int) ) ; | > /* see where that space starts */ | > printf( "%d" , ptr ) ; | > free( ptr ) ; | > /* it still points there, but dereferencing the pointer now is bad */ | > printf( "%d" , ptr ) ; | > return 1 ; | > } | > | > | > If you wrote a wrapper around free() that took a pointer to a pointer | > you _could_ then assign NULL to the second pointer, but that, of | > course, assumes that inside free() you have a valid pointer to | > dereference in the first place. | | A macro is easier (vile things that they are...)
Well, yeah, I was forgetting about them. | #define FREE(p) {if(p){free(p); (p)=NULL;}} However the thing to remember about macros is that they are textual substituation. It is effectively the same thing as writing the assignment yourself. | I've had occasion to use some replacement macros for malloc and realloc as | well. The realloc being the more useful. Inline functions are | cleaner though... inline functions are really no better than macros, and can even cause bugs (though surely that's just a sign of a buggy compiler). For a particular school project (C++ required) the profs had a working demo that we could run to verify our output (and clarify anything in the specs). They compiled it without debug symbols so we couldn't look at it in a debugger and reverse-engineer it. Their demo would crash with certain malformed input. One of the profs tried to figure it out, but once it was recompiled with debug symbols (which also turns off inlining, for that compiler at least) the program worked correctly. They had used inline functions extensively in their code. There's no real point to an inline function, just make it a regular function. The overhead of a function call isn't very big, especially nowadays. -D -- A)bort, R)etry, B)ang it with a large hammer