Skip to study material
← Question index

QUESTION 22 · Dynamic Memory

Compare malloc and calloc with a complete example.

5 marks

Answer in brief

Both functions obtain allocated storage, but their argument forms and initialisation differ.

Malloc

int *a = malloc(n * sizeof *a);

Calloc

int *b = calloc(n, sizeof *b);

Working

malloc takes one byte-count argument. calloc takes an element count and an element size. A successful call returns a suitably aligned pointer for the ordinary int objects used here. A failed non-zero request returns NULL. Always check the result before access.

Example trace

The program requests three ints with each function. It explicitly fills the malloc block with 1, 2 and 3, so their sum is 6. It then reads the calloc-created int elements, whose initial values are zero, and prints a sum of 0. Both blocks are freed.

Important distinctions

The all-zero-byte rule is not a universal promise of the floating value 0.0 or a null pointer representation for every type. The example specifically uses int. For arbitrary counts, validate multiplication before forming a malloc byte count; do not allow size_t arithmetic to wrap. This fixed request has a small known count.

Failure and complexity

If either allocation fails, the sample frees any successful allocation before returning. free(NULL) is permitted. Filling and summing n elements requires O(n) element work, and the allocated storage is O(n). Allocator internals have implementation-dependent costs; the traversal analysis is separate.

Comparison table

↔ Scroll horizontally on a small screen
Allocation functions
Featuremalloccalloc
ArgumentsByte countElement count and size
Initial contentsNot initialisedAll allocated bytes zeroed
Failure of non-zero requestNULLNULL
Releasefreefree

C program and output

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

int main(void)
{
    size_t n = 3;
    int *a = malloc(n * sizeof *a);
    int *b = calloc(n, sizeof *b);
    if (a == NULL || b == NULL) {
        free(a); free(b); puts("Allocation failed"); return 1;
    }
    int sum_a = 0, sum_b = 0;
    for (size_t i = 0; i < n; ++i) {
        a[i] = (int)i + 1;
        sum_a += a[i]; sum_b += b[i];
    }
    printf("Malloc sum = %d, calloc sum = %d\n", sum_a, sum_b);
    free(a); free(b);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Malloc sum = 6, calloc sum = 0

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 →