1 2 3 4 5 6 7 8 9 10

Remember, if you want to use malloc to obtain memory for a string, you must leave space for the '\0'terminator.

To give the space back to the system simply write

free(p);

To obtain space for N integers write

int* q = (int*) malloc ( N*(sizeof (int)) );

Note the necessary and different coercion (casting). Actually because malloc is a void* function it can be cast to point to any object.

callocis similar in many ways, but it initializes the memoryobtained to zero. More general and better.

To obtain N integers, each initialized to zero, write:

int* q = (int*) calloc (N, sizeof(int));

Similarly

free (q);

gives the space back to the system.

calloc is especially useful for acquiring space for a data structure element.

4 February, 1998

2

Copyright University of Alberta