Programs & Examples
Memory Allocation · Study material
A growing string builder with realloc()
Keep length and capacity next to the data, and double the capacity when it runs out. realloc(NULL, n) behaves like malloc(n), so the first append needs no special case.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct sb {
char *data;
size_t len, cap;
};
bool sb_append(struct sb *b, const char *s) {
size_t n = strlen(s);
if (b->len + n + 1 > b->cap) {
size_t cap = b->cap ? b->cap : 8;
while (cap < b->len + n + 1)
cap *= 2;
char *tmp = realloc(b->data, cap); /* realloc(NULL, n) works like malloc(n) */
if (tmp == NULL)
return false;
b->data = tmp;
b->cap = cap;
}
memcpy(b->data + b->len, s, n + 1);
b->len += n;
return true;
}
int main(void) {
struct sb b = {0};
const char *words[] = {"dynamic ", "memory ", "in ", "C"};
for (int i = 0; i < 4; i++)
if (!sb_append(&b, words[i]))
return 1;
printf("%s (len %zu, cap %zu)\n", b.data, b.len, b.cap);
free(b.data);
return 0;
}
dynamic memory in C (len 19, cap 32)
Jagged array: Pascal's triangle with rows of different lengths
An array of row pointers lets each row have its own size. If any row fails to allocate, free the rows already made before giving up.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int rows = 5;
int **t = malloc(rows * sizeof *t); /* an array of row pointers */
if (t == NULL)
return 1;
for (int r = 0; r < rows; r++) {
t[r] = malloc((r + 1) * sizeof *t[r]); /* row r has r + 1 numbers */
if (t[r] == NULL) {
while (r--)
free(t[r]);
free(t);
return 1;
}
t[r][0] = t[r][r] = 1;
for (int c = 1; c < r; c++)
t[r][c] = t[r - 1][c - 1] + t[r - 1][c];
}
for (int r = 0; r < rows; r++) {
for (int c = 0; c <= r; c++)
printf("%d ", t[r][c]);
printf("\n");
free(t[r]);
}
free(t);
return 0;
}
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1