Skip to content

Instantly share code, notes, and snippets.

@kay
Last active December 17, 2015 19:09
Show Gist options
  • Save kay/5658577 to your computer and use it in GitHub Desktop.
Save kay/5658577 to your computer and use it in GitHub Desktop.
tag_alloc
#define TAG_TYPE int
#define TAG_SIZE sizeof(TAG_TYPE)
#define VALID_START_TAG 0xDEADBEEF
#define VALID_END_TAG 0xCAFEBABE
#define TAG_INVALID_VALUE 0xBADC0DE5
#define PTR_START_TAG(memory) (TAG_TYPE *)(memory->ptr - TAG_SIZE)
#define PTR_END_TAG(memory) (TAG_TYPE *)(memory->ptr + memory->size)
typedef struct memory {
void * ptr;
size_t size;
} memory_t;
bool tag_alloc(memory_t * memory, size_t size) {
void * ptr = malloc(size + (2 * TAG_SIZE));
if (ptr == NULL) {
return false;
}
TAG_TYPE * startPtr = ptr;
*startPtr = VALID_START_TAG;
ptr += TAG_SIZE;
// Advance the first tag and the remainder of the buffer
TAG_TYPE * endPtr = ptr + size;
*endPtr = VALID_END_TAG;
memory->ptr = ptr;
memory->size = size;
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment