malloced structure initilization

Walter Bright bright at Data-IO.COM
Tue Feb 14 07:16:06 AEST 1989


In article <489 at madnix.UUCP> glasser at madnix.UUCP (Daniel Glasser) writes:
<If you need to initialize a structure allocated by a call to malloc()
<the best way to go about it is (for most modern compilers):
<	struct foreign *x;
<	if ((x = malloc(sizeof(*x))) == NULL)
<		panic("can't allocate...");
<	else
<		memset(x, 0, sizeof(*x));

Not true. If what you want is a 0 bit pattern, the best way is:
	struct foreign *x;
	if ((x = (struct foreign *) calloc(sizeof(*x),1)) == NULL)
		panic("can't allocate...");
calloc is a standard function, and is more commonly available than memset.



More information about the Comp.lang.c mailing list