Skip to content

Instantly share code, notes, and snippets.

@Hadaward
Last active October 15, 2024 15:36
Show Gist options
  • Select an option

  • Save Hadaward/80286dd55e6339f44b7f222cde6f1d55 to your computer and use it in GitHub Desktop.

Select an option

Save Hadaward/80286dd55e6339f44b7f222cde6f1d55 to your computer and use it in GitHub Desktop.
Utilities for managing the memory of initialized objects. By using "use(allocator, type)" you initialize a new object pointer that calls the code defined by "default(type)" if there is one to initialize the object's default values. By using "ret value" instead of "return value" you ensure that all objects initialized with use are freed from memory.
#include "gmdutil.h"
typedef struct Point {
int x;
int y;
} Point;
default(Point) {
self->x = 0;
self->y = 0;
}
int main() {
Point *p = use(malloc, Point);
if (p != NULL) {
printf("X: %d\nY: %d\n", p->x, p->y);
}
ret 0;
}
/*
If you don't want to use default,
then replace "default(Point)" by "nodefault(Point)",
this way the default system is ignored.
*/
#include "gmdutil.h"
typedef struct Point {
int x;
int y;
} Point;
nodefault(Point);
int main() {
Point *p = use(malloc, Point);
if (p != NULL) {
printf("X: %d\nY: %d\n", p->x, p->y);
}
ret 0;
}
#ifndef GMD_UTIL_H
#define GMD_UTIL_H
#include <stdio.h>
#include <stdlib.h>
#define MAX_MEMORY_ITEMS 64
static void *memory[MAX_MEMORY_ITEMS];
static int memory_idx = 0;
void *save_to_memory(void *ptr) {
if (memory_idx >= MAX_MEMORY_ITEMS) {
printf("Unable to allocate to memory because it's full.\n");
free(ptr);
return NULL;
}
memory[memory_idx] = ptr;
memory_idx++;
return ptr;
}
void free_memory() {
for (int i = 0; i < memory_idx; i++) {
if (memory[i] != NULL) {
free(memory[i]);
memory[i] = NULL;
}
}
memory_idx = 0;
}
#define use_default(name, ptr) ({\
if (__use_default__##name != NULL) {\
__use_default__##name(ptr);\
}\
ptr;\
})
#define use(allocator, type) ({\
type *ptr = (type *)(allocator(sizeof(type)));\
save_to_memory(use_default(type, ptr));\
})
#define ret free_memory(); return
#define default(type) void __use_default__##type(type *self)
#define nodefault(type) void (*__use_default__##type)(void *ptr) = NULL
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment