Building a string on the heap in C
Joining an unknown number of pieces: measure, allocate once, then copy.
#include <stdlib.h>
#include <string.h>
char *join(const char **parts, size_t n, const char *sep) {
size_t total = 1;
for (size_t i = 0; i < n; i++) {
total += strlen(parts[i]);
if (i + 1 < n) {
total += strlen(sep);
}
}
char *out = malloc(total);
if (out == NULL) {
return NULL;
}
size_t used = 0;
for (size_t i = 0; i < n; i++) {
size_t len = strlen(parts[i]);
memcpy(out + used, parts[i], len);
used += len;
if (i + 1 < n) {
size_t s = strlen(sep);
memcpy(out + used, sep, s);
used += s;
}
}
out[used] = '\0';
return out;
}
How it works
- Two passes avoid repeated reallocation.
- The total includes the separators and one byte for the NUL.
- The caller owns the result.
Keywords and builtins used here
NULLcharconstforifjoinreturnsize_t
The run, in numbers
- Lines
- 31
- Characters to type
- 529
- Tokens
- 196
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 124 seconds.
Step 4 of 4 in Copying & building, step 4 of 13 in Strings & text.