Re: OT: Language War (Re: "C" Manual)
On Thu, 3 Jan 2002 07:22:59 -0500, dman <dsh8290@rit.edu> 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...)
#define FREE(p) {if(p){free(p); (p)=NULL;}}
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...
#define REALLOC(p, s, str)\
{if ((s) > 0)\
{void *ptr = realloc (p, s);\
if (!ptr)\
{fprintf(stderr,"realloc(%p,%d) failed in %s\n", p, s, str);\
exit (EXIT_FAILURE);\
}\
else {(p) = ptr;}}
}\
}
Course, the REALLOC doesn't improve safety one whit (just a convenience).
--
Eric G. Miller <egm2@jps.net>
Reply to: