Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Created August 17, 2012 20:22
Show Gist options
  • Save wjlafrance/3382305 to your computer and use it in GitHub Desktop.
Save wjlafrance/3382305 to your computer and use it in GitHub Desktop.
Retain and release!
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
struct SObject
{
uint32_t retainCount;
void *buffer;
};
typedef struct SObject Object;
Object *alloc(size_t length);
Object *retain(Object *object);
Object *release(Object *object);
void dealloc(Object *object);
void expect(uint8_t condition, const char *message);
/**
* Allocate a retain-counted buffer n-bytes long.
*/
Object *alloc(size_t length)
{
Object *object = malloc(sizeof(Object));
object->retainCount = 0;
object->buffer = malloc(length);
return retain(object);
}
Object *retain(Object *object)
{
object->retainCount++;
return object;
}
Object *release(Object *object)
{
object->retainCount = object->retainCount - 1;
if (object->retainCount <= 0) {
dealloc(object);
return NULL;
} else {
return object;
}
}
/**
* Used by release to clean up the object
*/
void dealloc(Object *object)
{
free(object->buffer);
object->buffer = NULL;
free(object);
}
/**
* Yells when things break
*/
void expect(uint8_t condition, const char *message)
{
if (!condition) {
printf("assertion failed: %s\n", message);
}
}
/**
* Don't look at retain count. It's just a test. Don't look at it otherwise!
*/
int main(int argc, char **argv)
{
Object *object = alloc(1024);
expect(object->retainCount == 1, "object should have +1 retain");
expect(object != NULL, "buffer should exist");
retain(object);
expect(object->retainCount == 2, "object should have +2 retain");
release(object);
expect(object->retainCount == 1, "object should have +1 retain");
release(object);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment