A byte arena, without header casts
Can an unsigned char array implement malloc? It can store bytes. Here is the narrower, portable approach you can compile: keep metadata as real C objects, copy it into the arena with memcpy, and preserve the payload.
Free standalone C11 example and 14 checks. Run here or compile locally. Not arbitrary typed-object allocation or the guest lesson solution.
Go to the runnable C11 example ↓Runnable answer · C11 · No account
Copy objects into bytes. Copy bytes back into objects.
A real Header holds a payload length and a tag. memcpy stores its representation in an unsigned char array at offset 1, then retrieves it into another real Header. No pointer to a header is formed inside the array. The payload is just bytes.
Edit the byte-storage implementation
Start from the completed, verified implementation. Change the four helpers below, then run the unchanged 14-check harness. Keep the function names, signatures and external linkage (no static); the browser compiles the harness separately.
Read the fixed includes, Header type and storage contract
/* Heapcraft: byte-oriented storage, not arbitrary-object malloc.
* https://heapcraft.brainer.one/tools/byte-arena#byte-arena-example
* cc -std=c11 -Wall -Wextra -Werror -pedantic \
* heapcraft-byte-arena.c -o byte-arena
* ./byte-arena
*
* Contract: arena points to a live unsigned char array of at least cap
* bytes. Header inputs/outputs are real, separate, non-overlapping
* objects. Read only metadata previously written from a valid Header
* in this execution; this is not a parser for untrusted bytes or a
* portable file/network format. No Header pointer points into arena.
* Failure leaves storage/output unchanged. No reservation policy.
*/
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h> /* SIZE_MAX */
#include <stdio.h>
#include <string.h>
typedef struct {
size_t payload_size;
unsigned int tag;
} Header;
16 KB source maximum. Edits stay in this tab until you leave or reload; copy or download to keep them. Your source goes to Compiler Explorer: do not include private code or secrets. This is not saved account progress or lesson completion.
Read the unchanged 14-check harness
/* Checks remain active under -DNDEBUG. Compare fields, not padding. */
static unsigned tests, failures;
#define CHECK(label, condition) do { \
++tests; \
if (condition) { printf("PASS: %s\n", label); } \
else { ++failures; printf("FAIL: %s\n", label); } \
} while (0)
int main(void)
{
/* Offset 1 intentionally makes no Header alignment promise. */
enum { OFFSET = 1, PAYLOAD = 5 };
unsigned char arena[OFFSET + sizeof(Header) + PAYLOAD];
const unsigned char bytes[PAYLOAD] = {0x00, 0x41, 0xff, 0x7f, 0x23};
const size_t cap = sizeof arena;
const size_t start = OFFSET + sizeof(Header);
Header original = {PAYLOAD, 7};
Header decoded = {99, 99};
bool ready;
memset(arena, 0, cap);
/* Check integers before forming the payload pointer as well. */
ready = block_fits(cap, OFFSET, PAYLOAD);
CHECK("exact header-plus-payload capacity", ready);
if (!ready) return 1;
memcpy(arena + start, bytes, sizeof bytes);
CHECK("store metadata at byte offset 1",
store_header(arena, cap, OFFSET, &original));
CHECK("round-trip metadata fields",
load_header(arena, cap, OFFSET, &decoded) &&
decoded.payload_size == PAYLOAD && decoded.tag == 7);
CHECK("header write preserves payload bytes",
memcmp(arena + start, bytes, sizeof bytes) == 0);
original.tag = 42;
CHECK("update metadata and read it back",
store_header(arena, cap, OFFSET, &original) &&
load_header(arena, cap, OFFSET, &decoded) &&
decoded.payload_size == PAYLOAD && decoded.tag == 42);
CHECK("metadata update preserves payload and prefix",
memcmp(arena + start, bytes, sizeof bytes) == 0 &&
arena[0] == 0);
original.tag = 100;
CHECK("one-byte-short capacity rejects store without mutation",
!store_header(arena, cap - 1, OFFSET, &original) &&
load_header(arena, cap, OFFSET, &decoded) &&
decoded.tag == 42 &&
memcmp(arena + start, bytes, sizeof bytes) == 0);
decoded = (Header){99, 99};
CHECK("short payload capacity rejects load; output unchanged",
!load_header(arena, cap - 1, OFFSET, &decoded) &&
decoded.payload_size == 99 && decoded.tag == 99);
CHECK("short header capacity rejects load",
!load_header(arena, OFFSET + sizeof(Header) - 1,
OFFSET, &decoded) && decoded.tag == 99);
CHECK("end offset cannot hold a header",
!store_header(arena, cap, cap, &original) &&
!load_header(arena, cap, cap, &decoded));
CHECK("SIZE_MAX offset and payload rejected before pointers",
!store_header(arena, cap, SIZE_MAX, &original) &&
!load_header(arena, cap, SIZE_MAX, &decoded) &&
!block_fits(cap, OFFSET, SIZE_MAX));
CHECK("zero bytes fit at end; one byte does not",
fits(cap, cap, 0) && !fits(cap, cap, 1));
CHECK("null pointers rejected",
!store_header(NULL, cap, OFFSET, &original) &&
!store_header(arena, cap, OFFSET, NULL) &&
!load_header(NULL, cap, OFFSET, &decoded) &&
!load_header(arena, cap, OFFSET, NULL));
original.payload_size = 0;
CHECK("empty payload fits exact header capacity",
store_header(arena, OFFSET + sizeof(Header), OFFSET,
&original) &&
load_header(arena, OFFSET + sizeof(Header), OFFSET,
&decoded) && decoded.payload_size == 0 &&
memcmp(arena + start, bytes, sizeof bytes) == 0);
printf("%u/%u checks passed\n", tests - failures, tests);
return failures == 0 ? 0 : 1;
}
Test your implementation · 14 fixed checks
No compiler setup or account. Compile your current implementation against the fixed C11 harness. Copy and download include your current edits plus these same 14 checks for local use.
Runs use Compiler Explorer’s free GCC 13.2 sandbox, with a 30-second request limit. Availability can vary. Shared guest limits: at least 8 seconds between starts, 20 runs per network per UTC day, and shared capacity limits. This demonstration does not save or complete any lesson.
Compile and run locally
Download the file and open a terminal in its folder. With a C11 compiler such as GCC or Clang:
cc -std=c11 \
-Wall -Wextra -Werror \
-pedantic \
heapcraft-byte-arena.c \
-o byte-arena
./byte-arenaExpect 14/14 checks passed and exit status 0. A failed check prints FAIL and exits with status 1. Tests also stay enabled with -DNDEBUG.
On Windows, use a C11-capable toolchain and run .\byte-arena.exe. No extra libraries or Heapcraft account are required. Local runs remain separate from Heapcraft lesson progress.
What the checks establish
- Metadata round trips by field value, including a tag update.
- Exactly
1 + sizeof(Header) + 5bytes of capacity accept the header and payload. - One byte less rejects the operation; failed stores leave metadata and payload intact, and failed loads leave output unchanged.
- A short header, end offset,
SIZE_MAXoffset or length, and null pointers are rejected. - The five payload bytes, including zero and
0xff, survive header writes and updates. An empty payload fits exactly after the header.
“Byte” means a C byte. Header size and padding depend on your implementation. Tests compare metadata members, never incidental struct padding; memcmp is used only on the payload bytes.
Bounds before byte pointers
First check offset <= cap, then count <= cap - offset. Once the header fits, compare the payload length with cap - offset - sizeof(Header). No end-offset addition can wrap. Only after these integer checks may the helpers form arena + offset for the copy.
On load, check header capacity before copying into a local object, then check its decoded payload length before returning it. Capacity must describe the actual live array, not an invented larger size. Input and output headers must be separate real objects, not aliases of arena storage.
Portable C storage—not a portable wire format or malloc
The byte array keeps its declared type. Alignment alone does not authorize accessing it as a Header or an arbitrary caller-selected type. Copying the representation back into a real, suitably aligned header object is the key distinction. Offset 1 intentionally makes no header-alignment promise.
Read only representations previously copied from valid headers in this execution. Native sizes, endianness and padding make this unsuitable for files, network messages or untrusted input. The example demonstrates metadata storage and byte payload preservation; it has no allocation, free-list or reservation policy and is not production malloc.
Read the complete C11 source and 14 checks
/* Heapcraft: byte-oriented storage, not arbitrary-object malloc.
* https://heapcraft.brainer.one/tools/byte-arena#byte-arena-example
* cc -std=c11 -Wall -Wextra -Werror -pedantic \
* heapcraft-byte-arena.c -o byte-arena
* ./byte-arena
*
* Contract: arena points to a live unsigned char array of at least cap
* bytes. Header inputs/outputs are real, separate, non-overlapping
* objects. Read only metadata previously written from a valid Header
* in this execution; this is not a parser for untrusted bytes or a
* portable file/network format. No Header pointer points into arena.
* Failure leaves storage/output unchanged. No reservation policy.
*/
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h> /* SIZE_MAX */
#include <stdio.h>
#include <string.h>
typedef struct {
size_t payload_size;
unsigned int tag;
} Header;
/* Subtract only after checking: no overflowing end-offset addition. */
bool fits(size_t cap, size_t offset, size_t count)
{
return offset <= cap && count <= cap - offset;
}
bool block_fits(size_t cap, size_t offset, size_t payload)
{
return fits(cap, offset, sizeof(Header)) &&
payload <= cap - offset - sizeof(Header);
}
bool store_header(unsigned char *arena, size_t cap,
size_t offset, const Header *header)
{
if (arena == NULL || header == NULL ||
!block_fits(cap, offset, header->payload_size))
return false;
/* Only now form a byte pointer. Struct padding is copied too. */
memcpy(arena + offset, header, sizeof *header);
return true;
}
bool load_header(const unsigned char *arena, size_t cap,
size_t offset, Header *out)
{
Header decoded;
if (arena == NULL || out == NULL ||
!fits(cap, offset, sizeof decoded))
return false;
memcpy(&decoded, arena + offset, sizeof decoded);
if (!block_fits(cap, offset, decoded.payload_size))
return false;
*out = decoded;
return true;
}
/* Checks remain active under -DNDEBUG. Compare fields, not padding. */
static unsigned tests, failures;
#define CHECK(label, condition) do { \
++tests; \
if (condition) { printf("PASS: %s\n", label); } \
else { ++failures; printf("FAIL: %s\n", label); } \
} while (0)
int main(void)
{
/* Offset 1 intentionally makes no Header alignment promise. */
enum { OFFSET = 1, PAYLOAD = 5 };
unsigned char arena[OFFSET + sizeof(Header) + PAYLOAD];
const unsigned char bytes[PAYLOAD] = {0x00, 0x41, 0xff, 0x7f, 0x23};
const size_t cap = sizeof arena;
const size_t start = OFFSET + sizeof(Header);
Header original = {PAYLOAD, 7};
Header decoded = {99, 99};
bool ready;
memset(arena, 0, cap);
/* Check integers before forming the payload pointer as well. */
ready = block_fits(cap, OFFSET, PAYLOAD);
CHECK("exact header-plus-payload capacity", ready);
if (!ready) return 1;
memcpy(arena + start, bytes, sizeof bytes);
CHECK("store metadata at byte offset 1",
store_header(arena, cap, OFFSET, &original));
CHECK("round-trip metadata fields",
load_header(arena, cap, OFFSET, &decoded) &&
decoded.payload_size == PAYLOAD && decoded.tag == 7);
CHECK("header write preserves payload bytes",
memcmp(arena + start, bytes, sizeof bytes) == 0);
original.tag = 42;
CHECK("update metadata and read it back",
store_header(arena, cap, OFFSET, &original) &&
load_header(arena, cap, OFFSET, &decoded) &&
decoded.payload_size == PAYLOAD && decoded.tag == 42);
CHECK("metadata update preserves payload and prefix",
memcmp(arena + start, bytes, sizeof bytes) == 0 &&
arena[0] == 0);
original.tag = 100;
CHECK("one-byte-short capacity rejects store without mutation",
!store_header(arena, cap - 1, OFFSET, &original) &&
load_header(arena, cap, OFFSET, &decoded) &&
decoded.tag == 42 &&
memcmp(arena + start, bytes, sizeof bytes) == 0);
decoded = (Header){99, 99};
CHECK("short payload capacity rejects load; output unchanged",
!load_header(arena, cap - 1, OFFSET, &decoded) &&
decoded.payload_size == 99 && decoded.tag == 99);
CHECK("short header capacity rejects load",
!load_header(arena, OFFSET + sizeof(Header) - 1,
OFFSET, &decoded) && decoded.tag == 99);
CHECK("end offset cannot hold a header",
!store_header(arena, cap, cap, &original) &&
!load_header(arena, cap, cap, &decoded));
CHECK("SIZE_MAX offset and payload rejected before pointers",
!store_header(arena, cap, SIZE_MAX, &original) &&
!load_header(arena, cap, SIZE_MAX, &decoded) &&
!block_fits(cap, OFFSET, SIZE_MAX));
CHECK("zero bytes fit at end; one byte does not",
fits(cap, cap, 0) && !fits(cap, cap, 1));
CHECK("null pointers rejected",
!store_header(NULL, cap, OFFSET, &original) &&
!store_header(arena, cap, OFFSET, NULL) &&
!load_header(NULL, cap, OFFSET, &decoded) &&
!load_header(arena, cap, OFFSET, NULL));
original.payload_size = 0;
CHECK("empty payload fits exact header capacity",
store_header(arena, OFFSET + sizeof(Header), OFFSET,
&original) &&
load_header(arena, OFFSET + sizeof(Header), OFFSET,
&decoded) && decoded.payload_size == 0 &&
memcmp(arena + start, bytes, sizeof bytes) == 0);
printf("%u/%u checks passed\n", tests - failures, tests);
return failures == 0 ? 0 : 1;
}
The explanation behind the example
The article explains why declared byte arrays differ from malloc storage, and why alignment does not settle effective type. This page supplies the runnable byte-storage alternative.
Can an unsigned char array implement malloc in C? →A separate task to implement yourself
The free guest exercise asks you to implement aligned reservations in a 64-byte arena and run seven C tests. It uses an 8-byte policy without inline headers. Its unfinished starter is not this completed metadata example.
Try the free lessonQuestions or a source issue? heapcraft@brainer.one
