Explain dynamic memory allocation and its main functions.
5 marks
Answer in brief
Dynamic allocation requests storage while a program is running. The program manages the useful lifetime of that storage explicitly.
Main functions
malloc requests a number of bytes without initialising their contents.
calloc allocates space for a count of equal-sized objects and sets the allocated bytes to zero.
realloc changes the size of an existing allocated block, possibly moving it.
free releases an allocated block when it is no longer needed.
Typical sequence
Determine a valid element count and check that its byte-size calculation cannot overflow.
Request storage using a suitable allocation function.
Check for NULL before using the result.
Initialise the required elements and use only valid positions.
Release storage exactly once when ownership ends.
Example size expression
int *p = malloc(n * sizeof *p);
Meaning and precautions
sizeof *p gives the size of the intended element without evaluating a dereference in this ordinary int case. In C, the returned void * can be assigned to int * without a cast. The allocated object is not automatically released when the local pointer variable leaves scope. Losing the last useful pointer to a needed allocation can cause a memory leak.
Space and time
Storage for n integers is proportional to n, giving O(n) allocated space. Initialising or reading all n elements takes O(n) work. C does not specify one algorithm or universal Big-O bound for malloc itself, so do not claim that every allocation call is guaranteed constant time. The following topics supply complete examples.
Diagram or flowchart
Explain dynamic memory allocation and its main functions. · Download diagram
Related exam questions
Related questions in the dynamic memory category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.