Programming in C

(Barry) #1
Dynamic Memory Allocation 387

and could then proceed to call the callocfunction to reserve the appropriate number
of elements


dataPtr = (struct dataEntry *) calloc (n, sizeof (struct dataEntry));


Execution of the preceding statement proceeds as follows:



  1. The callocfunction is called with two arguments, the first specifying that storage
    for nelements is to be dynamically allocated and the second specifying the size of
    each element.

  2. The callocfunction returns a pointer in memory to the allocated storage area. If
    the storage cannot be allocated, the null pointer is returned.

  3. The pointer is type cast into a pointer of type “pointer to struct dataEntry” and
    is then assigned to the pointer variable dataPtr.


Once again, the value of dataPtrshould be subsequently tested to ensure that the allo-
cation succeeded. If it did, its value is nonnull.This pointer can then be used in the nor-
mal fashion, as if it were pointing to an array of n dataEntryelements. For example, if
dataEntrycontains an integer member called index,you can assign 100 to this member
as pointed to by dataPtrwith the following statement:


dataPtr->index = 100;


The freeFunction


When you have finished working with the memory that has been dynamically allocated
by callocor malloc,you should give it back to the system by calling the freefunc-
tion.The single argument to the function is a pointer to the beginning of the allocated
memory, as returned by a callocor malloccall. So, the call


free (dataPtr);


returns the memory allocated by the calloccall shown previously, provided that the
val ue of dataPtrstill points to the beginningof the allocated memory.
The freefunction does not return a value.
The memory that is released by freecan be reused by a later call to callocor
malloc.For programs that need to allocate more storage space than would otherwise be
available if it were all allocated at once, this is worth remembering. Make certain you
give the freefunction a valid pointer to the beginning of some previously allocated
space.
Dynamic memory allocation is invaluable when dealing with linked structures, such
as linked lists.When you need to add a new entry to the list, you can dynamically allo-
cate storage for one entry in the list and link it into the list with the pointer returned by
callocor malloc.For example, assume that listEndpoints to the end of a singly
linked list of type struct entry, defined as follows:

Free download pdf