Skip to study material
← Question index

QUESTION 24 · Dynamic Memory

Explain safe use of realloc and free with an example.

5 marks

Answer in brief

realloc changes an allocation’s size. free releases storage obtained through the allocation family.

Safe pattern

int *temporary = realloc(p, new_count * sizeof *p);
if (temporary == NULL) {
    /* p still identifies the original block for this non-zero request */
} else {
    p = temporary;
}

What is preserved

On success, the old contents are preserved up to the smaller of the old and new sizes. A larger block’s added bytes are not automatically initialised. The allocation may move. The old pointer must no longer be used after a successful realloc, even when the returned address appears unchanged.

Example trace

The sample allocates two ints and stores 1 and 2. It requests space for four ints using a temporary pointer. After success, it stores 3 and 4 in the new positions and displays 1, 2, 3, 4. If growth fails, it frees the still-valid original block and exits.

Free and ownership

Pass free a valid currently allocated base pointer, or NULL. Do not free an interior element pointer, an automatic array or the same allocation twice. After freeing p, assigning p = NULL avoids retaining a dangling value in that variable. Other aliases are not automatically changed.

Limits and complexity

Use a validated non-zero new size and check multiplication for overflow. This lesson avoids the special zero-size realloc cases. A reallocation may need to copy retained data; its allocator cost is implementation-dependent. The explicit initialisation and printing of n values take O(n) work, and storage for n ints is O(n).

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int *p = malloc(2 * sizeof *p);
    if (p == NULL) { puts("Allocation failed"); return 1; }
    p[0] = 1; p[1] = 2;
    int *temporary = realloc(p, 4 * sizeof *p);
    if (temporary == NULL) { free(p); puts("Allocation failed"); return 1; }
    p = temporary;
    p[2] = 3; p[3] = 4;
    for (int i = 0; i < 4; ++i) { printf("%d\n", p[i]); }
    free(p);
    p = NULL;
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

1
2
3
4

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 →