section 7.8.5: Storage Management

The important thing to know about malloc and free and friends is to be careful when calling them. It is easy to abuse them, either by using more space than you ask for (that is, writing beyond the ends of an allocated block) or by continuing to use a pointer after the memory it points to has been freed (perhaps because you had several pointers to the same block of memory, and you forgot that when you freed one pointer they all became invalid). malloc-related bugs can be difficult and frustrating to track down, so it's good to use programming practices which help to assure that the bugs don't happen in the first place. (One such practice is to make sure that pointer variables are set to NULL when they don't point anywhere, and to occasionally check pointer values--for instance at entry to an important pointer-using function--to make sure that they're not NULL.)

As we mentioned on page 142 in section 6.5, it is no longer necessary (that is, in ANSI C) to cast malloc's value to the appropriate type, though it doesn't hurt to do so.

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995, 1996 // mail feedback