Common malloc/free practice violates ANSI standard ?

andre andre at targon.UUCP
Wed Oct 18 19:31:46 AEST 1989


In article <1989Oct14.043811.669 at anucsd.oz> bdm at anucsd.oz (Brendan McKay) writes:

>Consider the following piece of code, where OBJ is an arbitrary type name.

>        OBJ *objptr;

>        objptr = (OBJ*)malloc( sizeof(OBJ) );
>        ...
>        free( (void*)objptr );
>
>This use of malloc() and free() is of course very commonplace.  [In fact,

Correct.

>malloc() returns a value of type void*, "suitably aligned so that it may be
>assigned to a pointer to any type of object and then used to access such an
>object..." (Section 4.10.3).  Thus, it is clear that we may use the value
>assigned to objptr without worry.  The trouble comes with the call to free(),
>who's argument must "match a pointer earlier returned by the [malloc] function".

The fact that you conclude that the pointer can be changed in value
when cast from void * to <type> * is wrong, because free() could never
know what pointer you used and thus howmany bytes back it much go to
find the pionters of the free list that probably precede your buffer.

This means that when malloc makes sure all types of pointers are
be accomodated, it rounds your request up *and* makes sure that
the address you get is already alligned for the object with the biggest
alignment gap. Meaning that on msdos you are likely to get only even
addresses from malloc. On most unixes addresses on a four byte boundary
and on machines where some type need 8 or 16 or 32 byte boundaries
you get 8 or 16 or 32 byte boundary pointers back from malloc().

You will say that on a big-boundary machine it is not efficient to ask for
10 buffers of 2 char because it will take at least say 10 * 16 byte.
But that is the price you pay for one routine that handles all requests.
You can always make your own char_malloc that askes bigger blocks from malloc
and gives out buffers from that block with byte allingment.

-- 
The mail|    AAA         DDDD  It's not the kill, but the thrill of the chase.
demon...|   AA AAvv   vvDD  DD        Ketchup is a vegetable.
hits!.@&|  AAAAAAAvv vvDD  DD                    {nixbur|nixtor}!adalen.via
--more--| AAA   AAAvvvDDDDDD    Andre van Dalen, uunet!hp4nl!targon!andre



More information about the Comp.std.c mailing list