Dynamic structures and allocation:
- The Pascal new statement allocates heap storage for an object of a different type. There are
several allocation operators in C, the most important one of which is malloc --- memory
allocation.
- malloc
takes one argument, a number of bytes, and returns the address of a block of
memory of that size. Thus the result of a malloc command is a pointer, by default a pointer to
type void. Safe use of malloc thus requires (a) that the argument be of the form
“sizeof ( desired type )”, and (b) that the result be cast to type “pointer to desired type”.
The following is an example of types and allocation associated with a dynamic tree (and also use of the-
> operator).
struct tree { int data;
struct tree *left, *right;} *root;
root = (struct tree *) malloc (sizeof (struct tree));
root -> data = 1;
left = (struct tree *) malloc (sizeof (struct tree));
right = (struct tree *) malloc (sizeof (struct tree));
- Space allocated with malloc, if still accessible through the symbol table (that is, not garbage)
can be reclaimed with dealloc. Of course, if the pointer to that space is not reassigned, it
becomes a dangling pointer. Unless the pointer is to be immediately reused with a malloc or
assignment, it is probably better to cast it to (void *) immediately.