pointers-memory · intermediate · ~15 min
Compute total size, allocate once, and copy — avoid the trap of growing buffers in a loop with `realloc` for no reason.
Join three strings into one freshly allocated string, sizing the buffer correctly in a single allocation.
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.
Three non-NULL, NUL-terminated strings a, b, c (any of them may be empty).
A malloc-ed NUL-terminated string holding the concatenation. The caller frees it. Return NULL if allocation fails.
concat3("foo", "-", "bar") -> "foo-bar"
concat3("", "", "") -> ""
concat3("abc", "def", "ghi") -> "abcdefghi"
"" (still a valid allocation, just the NUL byte).+1 for the terminator.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.
Three non-NULL NUL-terminated strings a, b, c.
A malloc'd string a+b+c owned by the caller; NULL on allocation failure.
Single allocation sized to the total length plus 1 for the NUL.
#include <stdlib.h>
#include <string.h>
char *concat3(const char *a, const char *b, const char *c) {
/* TODO */
return NULL;
}
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.
Either input is empty — concat still works. Both empty — returns a 1-byte buffer holding just the NUL.
O(strlen(a) + strlen(b)).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.