pointers-memory · intermediate · ~22 min

Concat three strings (no leaks)

Compute total size, allocate once, and copy — avoid the trap of growing buffers in a loop with `realloc` for no reason.

Challenge

Join three strings into one freshly allocated string, sizing the buffer correctly in a single allocation.

Task

Implement char *concat3(const char *a, const char *b, const char *c) that returns a newly allocated string equal to a followed by b followed by c. No main — the grader calls it.

Input

Three non-NULL, NUL-terminated strings a, b, c (any of them may be empty).

Output

A malloc-ed NUL-terminated string holding the concatenation. The caller frees it. Return NULL if allocation fails.

Example

concat3("foo", "-", "bar")     ->   "foo-bar"
concat3("", "", "")            ->   ""
concat3("abc", "def", "ghi")   ->   "abcdefghi"

Edge cases

  • All-empty inputs produce "" (still a valid allocation, just the NUL byte).

Rules

  • Compute the total length first and allocate once (do not grow the buffer in a loop); remember the +1 for the terminator.

Why this matters

Transfer exercise: apply the lesson to a complete function contract.

Input format

Three non-NULL, NUL-terminated strings a, b, c (any of them may be empty).

Output format

A malloc-ed NUL-terminated string holding the concatenation. The caller frees it. Return NULL if allocation fails.

Constraints

Three non-NULL live terminated strings, borrowed and unmodified. Return one owned terminated concatenation, or NULL if combined size overflows or allocation fails.

Starter code

#include <stdlib.h>
#include <string.h>

char *concat3(const char *a, const char *b, const char *c) {
    /* TODO */
    return NULL;
}

Common mistakes

Counting only two inputs, omitting the terminator, or unchecked length addition.

Edge cases to handle

Any or all of the three strings empty; one byte for an all-empty result; combined-size overflow.

Complexity

O(strlen(a) + strlen(b)).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.