Skip to study material
← Question index

QUESTION 20 · Dynamic Memory

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

  1. malloc requests a number of bytes without initialising their contents.
  2. calloc allocates space for a count of equal-sized objects and sets the allocated bytes to zero.
  3. realloc changes the size of an existing allocated block, possibly moving it.
  4. free releases an allocated block when it is no longer needed.

Typical sequence

  1. Determine a valid element count and check that its byte-size calculation cannot overflow.
  2. Request storage using a suitable allocation function.
  3. Check for NULL before using the result.
  4. Initialise the required elements and use only valid positions.
  5. 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

CodeBhavya illustration of allocation.
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.

  • September/October 2021 · Q8(b) · 8 marks

    Write a note on dynamic memory allocation.

    Paper P01 · page 1
  • March/April 2023 · Q1(h) · 3 marks

    Write the syntax of malloc().

    Paper P02 · page 1

View this category in the exam question bank →