caff-previewer/src/magic_memory.c

77 lines
1.5 KiB
C
Raw Normal View History

2020-11-03 16:42:53 +01:00
//
// Created by marcsello on 03/11/2020.
//
#include <stdlib.h>
#include "magic_memory.h"
2020-11-03 18:25:18 +01:00
magic_memory_context_t *magic_memory_begin(void) {
magic_memory_context_t *new_mm = (magic_memory_context_t *) malloc(sizeof(magic_memory_context_t));
2020-11-03 16:42:53 +01:00
if (new_mm == NULL) {
return NULL;
}
new_mm->ptr = NULL;
new_mm->next = NULL;
return new_mm;
}
2020-11-03 18:25:18 +01:00
void *magic_malloc(magic_memory_context_t *magic_memory, size_t size) {
2020-11-03 16:42:53 +01:00
2020-11-03 18:25:18 +01:00
magic_memory_context_t *mm = (magic_memory_context_t *) malloc(sizeof(magic_memory_context_t));
2020-11-03 16:42:53 +01:00
if (mm == NULL) {
return NULL;
}
void *new_ptr = malloc(size);
if (new_ptr == NULL) {
free(mm);
return NULL;
}
mm->ptr = new_ptr;
mm->next = NULL;
2020-11-03 18:25:18 +01:00
magic_memory_context_t *p = magic_memory;
2020-11-03 16:42:53 +01:00
while (p->next != NULL) {
p = p->next;
}
p->next = mm;
return new_ptr;
}
2020-11-03 18:25:18 +01:00
void magic_free(magic_memory_context_t *magic_memory, void *ptr) {
2020-11-03 16:42:53 +01:00
2020-11-03 18:25:18 +01:00
magic_memory_context_t *p = magic_memory;
2020-11-03 16:42:53 +01:00
while (p != NULL) {
if (p->ptr == ptr) {
free(p->ptr);
p->ptr = NULL;
}
p = p->next;
}
}
2020-11-03 18:25:18 +01:00
void magic_cleanup(magic_memory_context_t *magic_memory) {
2020-11-03 16:42:53 +01:00
2020-11-03 18:25:18 +01:00
magic_memory_context_t *p = magic_memory;
2020-11-03 16:42:53 +01:00
while (p != NULL) {
if (p->ptr != NULL) {
free(p->ptr); // Free up the block this chain element points to
}
2020-11-03 18:25:18 +01:00
magic_memory_context_t* p_old = p;
2020-11-03 16:42:53 +01:00
p = p->next;
free(p_old); // Free up the chain piece itself
}
}