Question on Portable Memory Management Syntax

Doug Gwyn gwyn at smoke.brl.mil
Wed Feb 20 11:00:27 AEST 1991


In article <1991Feb18.133400.11870 at dit.upm.es> esink at turia.dit.upm.es (Eric Wayne Sink) writes:
>   'handles' instead of pointers.

Yes, Apple uses these on the IIGS also.  Generally such an approach
permits "garbage collection" and compaction of the arena by the
memory allocation subsystem.

Unless you are willing to implement and maintain your own garbage-
collecting storage allocator (which from practical experience I
would recommend against except in cases where it really is needed),
I would suggest that you define a common interface that takes the
desired type and a pointer to the variable into which the handle/
pointer is to be put, rather than mallocing the handle variable.
I.e.

#if MAC
/* *Handle() should be declared here, probably by some MPW header */
#define	Via(ap)		(*(ap))
#define	MyAlloc(t,ap)	(((ap) = (**(t))NewHandle(sizeof(t))) != NULL)
#define	MyFree(ap)	DisposeHandle((void **)(ap))
#else
/* malloc() and free() should be declared here, perhaps via <stdlib.h> */
#define	Via(ap)		(ap)
#define	MyAlloc(t,ap)	(((ap) = (*(t))malloc(sizeof(t))) != NULL)
#define	MyFree(ap)	free((void *)(ap))
#endif
...
	struct mystruct *Via(theHandle);
	if ( MyAlloc( struct mystruct, theHandle ) )
		Via(theHandle)->someMember = whatever;

If "Via" has too many characters for your taste, feel free to use
a shorter macro name.  MyAlloc() could obviously be designed to
have a different interface more like traditional malloc(), but I
found it convenient to package the test for allocation failure
into the macro.



More information about the Comp.lang.c mailing list