Initialization (was: Variable dimensioning in fortran)

Leo de Wit leo at philmds.UUCP
Tue Jun 28 22:13:50 AEST 1988


In article <734 at vsi.UUCP> friedl at vsi.UUCP (Stephen J. Friedl) writes:
  [stuff about calloc and its drawbacks deleted]...
>This has been my approach to a Q&D allocator for some
>kind of arbitrary data type:
>
>/*
> * objalloc()
> *
> *	Return one initialized item.
> */
>
>typedef struct object	OBJ;
>
>OBJ *
>objalloc()
>{
>static OBJ dummy;	/* guaranteed to be "the right" zeros	*/
>OBJ	   *p;
>
>	p = (OBJ *)Malloc(sizeof(*p));	/* does error checking internally */
>
>	*p = dummy;			/* do a *real* initialization	  */
>
>	return(p);
>}

Nice idea, but...
a) what if you want to initialize several different types? Each type
will need its own initialization function.
b) If sizeof(OBJ) is large you waste a large variable. No so terrible
on a VAX, but what to think of PC's?
c) the structure assignment: is that correct (i.e. does ANSI allow it)?
K&R says that it 'draws an error message', but 'In the future, it is
expected that these operations,...., will be allowed'.
d) If b) is not important and a) is, a macro could do the trick:

#define OBJALLOC(p,type)           \
{                                  \
    static type dummy;             \
    p = (type *)Malloc(sizeof(*p));\
    *p = dummy;		              \
}

I'd rather have the compiler supply the functionality, if that was
possible , for instance by a keyword that translates to a runtime
(evt. inline) function being called with a pointer to the object and a
parameter indicating the type (just philosofing).
If I'm correct the bss is initialized when an image gets loaded (not
yet present in the program file) so there should be functions that
provide these initializations. Perhaps someone that is familiar with
this stuff cares to comment?

        Leo.



More information about the Comp.lang.c mailing list