Skip to content

Instantly share code, notes, and snippets.

@carlos-jenkins
Created May 5, 2015 20:08
Show Gist options
  • Save carlos-jenkins/a0dbcdb4a8f81e67fdcd to your computer and use it in GitHub Desktop.
Save carlos-jenkins/a0dbcdb4a8f81e67fdcd to your computer and use it in GitHub Desktop.
Bytes structure in C
// Bytes structure to handle the data pointer and size tuple together
// and using a single heap allocation
// gcc bytes.c -o bytes
// ./bytes
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct
{
size_t size;
uint8_t* data;
} bytes;
bytes* new_bytes(size_t size)
{
if (size == 0) {
return NULL;
}
bytes* b = (bytes*) malloc(sizeof(bytes) + size);
if (b == NULL) {
return NULL;
}
b->size = size;
b->data = (uint8_t*)b + sizeof(bytes);
return b;
}
int main()
{
bytes* b = new_bytes(30);
if (b == NULL) {
printf("Bytes could not be allocated.\n");
return -1;
}
printf(
"Bytes (struct of %zu bytes) located at %p, with data of "
"size at %zu starting at %p\n",
sizeof(bytes), b, b->size, b->data
);
free(b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment