Sequence a safe array-growth procedure

A C routine owns a live integer array through p and records its element capacity in capacity. It must grow the array to n elements, where n is positive and greater than capacity. All existing elements are initialized, and the required headers are included. The variables n, capacity, and bytes have type size_t, and tmp has type int *.


Arrange this procedure in execution order. The routine must check that the requested byte count is representable before performing the multiplication. A rejected size or failed resize exits the procedure while retaining the original array. The final initialization step must use the updated owning pointer p.

  1. 1.

    Using the updated p, initialize elements from the old capacity through n - 1 before reading them.

  2. 2.

    Save the old capacity, assign tmp to p, and update capacity to n.

  3. 3.

    Compute and store the requested byte count: bytes = n * sizeof *p.

  4. 4.

    Reject the request if n > SIZE_MAX / sizeof *p.

  5. 5.

    Call realloc(p, bytes) and store its result in tmp.

  6. 6.

    Test tmp for NULL; on failure, exit without changing p or capacity.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Dynamic Memory Questions: