effect of free()

Walter Bright bright at Data-IO.COM
Thu Aug 17 03:56:57 AEST 1989


In article <320 at cubmol.BIO.COLUMBIA.EDU> ping at cubmol.UUCP (Shiping Zhang) writes:
>Many people said that after free()
>is called, the pointer used as the argument to free() is still valid
>and can be used IF NO (mc)alloc()'s are called after the call to free().

This is NOT true of all implementations of free(). Under Zortech C, the
size of a freelist entry (6 bytes) is larger than the size (2 bytes)
of the header of an allocated block. So when you free a block, the first
4 bytes of it get trashed.

A pox on anyone who writes code like:
	for (p = listhead; p; p = p->next)
		free(p);

Write it like:
	for (p = listhead; p; p = pn)
	{	pn = p->next;
		free(p);
	}

Program defensively. Always assume:
1. Calls to free() invalidate any pointers into that memory block.
2. realloc() always shifts the location of the block.



More information about the Comp.lang.c mailing list