Simvik

Allocate a variable-length packet

Build a heap object with a flexible array member. A medium embedded C problem (Structs, unions and memory layout), run and graded in the browser.

medium · Structs, unions and memory layout · flexible-array · heap

A flexible array member lets one allocation hold a header and a payload of any length.

Allocate a packet_t with room for exactly len payload bytes, set its len, copy the len bytes from data into it and return it. Return NULL if the allocation fails. The caller frees the packet with free.

Starter code

packet_t *packet_create(const uint8_t *data, uint8_t len) {
  // One malloc for the header plus the payload.
  return NULL;
}

Example tests

Three payload bytes

const uint8_t d[] = { 1, 2, 3 };
packet_t *p = packet_create(d, 3);
printf("%u %u %u %u\n", p->len, p->data[0], p->data[1], p->data[2]);
free(p);

Expected output:

3 1 2 3

Empty payload

packet_t *p = packet_create(NULL, 0);
printf("%s %u\n", p ? "ok" : "null", p ? p->len : 99);
free(p);

Expected output:

ok 0

Learn it first

More Structs, unions and memory layout problems