Implemented memory management

This commit is contained in:
Pünkösd Marcell 2020-11-03 16:42:53 +01:00
parent bc6c2bd0c1
commit fba1b6487f
4 changed files with 107 additions and 2 deletions

View File

@ -3,4 +3,4 @@ project(caff_previewer C)
set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD 11)
add_executable(caff_previewer src/main.c) add_executable(caff_previewer src/main.c src/magic_memory.c src/magic_memory.h)

77
src/magic_memory.c Normal file
View File

@ -0,0 +1,77 @@
//
// Created by marcsello on 03/11/2020.
//
#include <stdlib.h>
#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
}
}

18
src/magic_memory.h Normal file
View File

@ -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

View File

@ -1,6 +1,16 @@
#include <stdio.h> #include <stdio.h>
#include <string.h>
#include "magic_memory.h"
int main() { 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; return 0;
} }