Skip to content

Instantly share code, notes, and snippets.

@emctague
Created May 8, 2019 16:06
Show Gist options
  • Save emctague/0d7907c9c64c398138c0e422659a2e13 to your computer and use it in GitHub Desktop.
Save emctague/0d7907c9c64c398138c0e422659a2e13 to your computer and use it in GitHub Desktop.
memo [C Memory Management]
#include "memo.h"
#include <stdlib.h>
int main (int argc, char** argv)
{
// We initialize our memo set
memo_set* set = memo_set_new ();
// We make a thing and add it to the memo set
void* someData = malloc(20);
memo_set_add (set, someData, free);
// We make another thing and add it to the memo set
void* moreData = malloc(30);
memo_set_add (set, moreData, free);
// ---- JUST SO YOU KNOW! ----
// A memo set can be used for more than just `free` - any function
// that takes a single pointer argument is fair game!
// For example, I'm using a memo_set to destroy graphics objects in one project.
//
// We do some stuff with our various objects...
// ...
// We're done, so we clean up!
memo_set_free (set);
}
#include "memo.h"
#include <stdlib.h>
memo_set* memo_set_new ()
{
memo_set* set = malloc(sizeof(memo_set));
set->size = 0;
set->objects = 0;
return set;
}
void memo_set_add (memo_set* set, void* object, void (*free)(void*))
{
set->size++;
set->objects = realloc(set->objects, set->size * sizeof(memo_object));
set->objects[set->size - 1].object = object;
set->objects[set->size - 1].free = free;
}
void memo_set_free (memo_set* set)
{
for (int i = 0; i < set->size; i++) {
set->objects[i].free(set->objects[i].object);
}
free (set->objects);
free (set);
}
// memo
// Memory management lists system
#pragma once
//! An object and its freeing operation
typedef struct {
void* object;
void (*free)(void*);
} memo_object;
//! A memory management object set
typedef struct {
memo_object* objects;
int size;
} memo_set;
//! Initialize a memo set
memo_set* memo_set_new ();
//! Add an object to the memo set
void memo_set_add(memo_set* set, void* object, void (*free)(void*));
//! Free this memo set and its contents
void memo_set_free(memo_set* set);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment