Chapter 7 Dynamic Storage Allocation


Dynamic storage allocation :
Dynamic storage allocation can be especially useful if the programmer is not sure of the amount of data the program will have to process. Using dynamic storage, allocation, the programmer does not have to allocate any storage that will not be used by the program. The sizeof operator is most commonly used when it is coupled with a function allocating storage dynamically.
Objectives :
In order to dynamically allocate storage in a c program, the programmer should be able to use the following.
1. sizeof :
sizeof operator return the size in unsigned int or unsigned long of its operand. We may use the unary operator sizeof to tell us the sizeof any variable.
Example :
sizeof(int)
(sizeof return two)
2. malloc :
malloc is library function that allocates storage for objects that have not been declared (dynamically). malloc is used by parsing to it the amount of storage wanted, malloc allocates the storage from a pool of free storage.
Format :
fp=(float *) malloc (sizeof(float));
If malloc can't find enough storage, it will return 0.
3. calloc :
Like malloc,calloc is also used to allocate storage for objects. calloc is used to allocate arrays
Format :
void *calloc(size_t nitems, size_t size);
note : where first argument is no of elements in a array, and second argument is size of bytes.
4. free :
Free is used to free space previously obtained with one of allocation functions.
format :
void *free(void *ptr);