pointers-memory · intermediate · ~15 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

Implement char *concat3(const char *a, const char *b, const char *c) returning a newly allocated string containing the concatenation of the three inputs. The caller frees the result. None of the inputs are NULL.

Why this matters

Joining two strings into a freshly allocated buffer is the simplest non-trivial use of malloc + strlen + strcpy. It teaches you why every dynamic-string library exists.

Starter code

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

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

Common mistakes

Forgetting +1 for the NUL terminator (off-by-one buffer overflow). Using strcpy + strcat unbounded. Returning the buffer without telling the caller they own it.

Edge cases to handle

Either input is empty — concat still works. Both empty — returns a 1-byte buffer holding just the NUL.

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.