Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Garbage Collector #40

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ OBJ_DIR := obj
SRC_DIR := src


MODULES := parser executer tokenizer utils map prompt command ast built_in env error print wildcard new
MODULES := parser executer tokenizer utils map prompt command ast built_in env error print wildcard new gc

SRC_DIRS := $(addprefix src/,$(MODULES))
OBJ_DIRS := $(addprefix obj/,$(MODULES))
Expand Down Expand Up @@ -64,7 +64,8 @@ src/tokenizer/tokenize_word.c src/tokenizer/tokenizer.c src/utils/close.c \
src/utils/node_type_tostr.c src/utils/print_token.c src/utils/utils.c \
src/utils/utils_print.c src/wildcard/check_end.c src/wildcard/check_match.c \
src/wildcard/check_start.c src/wildcard/compare_char.c \
src/wildcard/vector_append_all.c src/wildcard/wildcard.c
src/wildcard/vector_append_all.c src/wildcard/wildcard.c \
src/gc/gc.c

OBJS := $(patsubst $(SRC_DIR)/%.c,$(OBJ_DIR)/%.o,$(SRCS))

Expand Down
40 changes: 40 additions & 0 deletions src/gc/gc.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@

#include "gc.h"
#include "vector.h"

static t_pvec *get_garbages()
{
static t_pvec *garbages;

if (garbages == NULL)
garbages = pvec_new(10);
return (garbages);
}

void gc()
{
t_pvec *garbages;
int index;

garbages = get_garbages();
index = garbages->len;
while (index >= 0)
{
free(garbages->arr[index]);
garbages->arr[index] = NULL;
garbages->len -= 1;
index--;
}
}

void *new(size_t size)
{
void *allocated;
t_pvec *garbages;

allocated = malloc(size);
garbages = get_garbages();
pvec_append(garbages, allocated);
return (allocated);
}

22 changes: 22 additions & 0 deletions src/gc/gc.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

#ifndef GC_H
# define GC_H
# include <stdlib.h>

/**
* Flushes all data that allocated.
* It should be used only when exiting the program
*
*/
void gc();

/**
* The new() function allocates a memory area.
* It differs from malloc(t_size) in that when you use new(t_size),
* the allocated memory is tracked for garbage collection with gc().
*
* @param size size of the data will be allocated
*/
void *new(size_t size);

#endif