diff --git a/CMakeLists.txt b/CMakeLists.txt index 32e7ca7..dfbf35e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,4 +3,4 @@ project(caff_previewer C) set(CMAKE_C_STANDARD 11) -add_executable(caff_previewer src/main.c) \ No newline at end of file +add_executable(caff_previewer src/main.c src/magic_memory.c src/magic_memory.h) \ No newline at end of file diff --git a/src/magic_memory.c b/src/magic_memory.c new file mode 100644 index 0000000..8f25b3d --- /dev/null +++ b/src/magic_memory.c @@ -0,0 +1,77 @@ +// +// Created by marcsello on 03/11/2020. +// +#include + +#include "magic_memory.h" + + +magic_memory_t *magic_memory_begin(void) { + magic_memory_t *new_mm = (magic_memory_t *) malloc(sizeof(magic_memory_t)); + + if (new_mm == NULL) { + return NULL; + } + + new_mm->ptr = NULL; + new_mm->next = NULL; + + return new_mm; +} + +void *magic_malloc(magic_memory_t *magic_memory, size_t size) { + + magic_memory_t *mm = (magic_memory_t *) malloc(sizeof(magic_memory_t)); + + 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; + + magic_memory_t *p = magic_memory; + while (p->next != NULL) { + p = p->next; + } + + p->next = mm; + return new_ptr; +} + +void magic_free(magic_memory_t *magic_memory, void *ptr) { + + magic_memory_t *p = magic_memory; + while (p != NULL) { + if (p->ptr == ptr) { + free(p->ptr); + p->ptr = NULL; + } + p = p->next; + } + +} + + +void magic_cleanup(magic_memory_t *magic_memory) { + + magic_memory_t *p = magic_memory; + while (p != NULL) { + + if (p->ptr != NULL) { + free(p->ptr); // Free up the block this chain element points to + } + magic_memory_t* p_old = p; + p = p->next; + free(p_old); // Free up the chain piece itself + } + + +} \ No newline at end of file diff --git a/src/magic_memory.h b/src/magic_memory.h new file mode 100644 index 0000000..d543ee8 --- /dev/null +++ b/src/magic_memory.h @@ -0,0 +1,18 @@ +// +// Created by marcsello on 03/11/2020. +// + +#ifndef CAFF_PREVIEWER_MAGIC_MEMORY_H +#define CAFF_PREVIEWER_MAGIC_MEMORY_H + +typedef struct magic_memory_t { + void* next; + void *ptr; +} magic_memory_t; + +magic_memory_t* magic_memory_begin(void); +void* magic_malloc(magic_memory_t* magic_memory, size_t size); +void magic_free(magic_memory_t* magic_memory, void* ptr); +void magic_cleanup(magic_memory_t* magic_memory); + +#endif //CAFF_PREVIEWER_MAGIC_MEMORY_H diff --git a/src/main.c b/src/main.c index f26b97c..fce5704 100644 --- a/src/main.c +++ b/src/main.c @@ -1,6 +1,16 @@ #include +#include + +#include "magic_memory.h" int main() { - printf("Hello, World!\n"); + magic_memory_t* magic_run = magic_memory_begin(); + + char* str = (char*)magic_malloc(magic_run, 120); + strcpy(str,"Test string! Hello world!!"); + printf("%s",str); + //magic_free(magic_run, str); + magic_cleanup(magic_run); // Free all memory used automagically + return 0; }