#15 Fixed some of the worst memory leaks

This commit is contained in:
2022-08-22 20:51:09 +01:00
parent b675c4c1bd
commit 08e2adab50
8 changed files with 22 additions and 5 deletions

View File

@@ -531,7 +531,7 @@ void writeCompiler(Compiler* compiler, Node* node) {
void freeCompiler(Compiler* compiler) {
freeLiteralArray(&compiler->literalCache);
FREE(unsigned char, compiler->bytecode);
FREE_ARRAY(unsigned char, compiler->bytecode, compiler->capacity);
compiler->bytecode = NULL;
compiler->capacity = 0;
compiler->count = 0;

View File

@@ -32,8 +32,6 @@ void initInterpreter(Interpreter* interpreter) {
}
void freeInterpreter(Interpreter* interpreter) {
FREE_ARRAY(char, interpreter->bytecode, interpreter->length);
//since these are dynamically allocated, free them manually
for (int i = 0; i < interpreter->literalCache.count; i++) {
if (IS_ARRAY(interpreter->literalCache.literals[i]) || IS_DICTIONARY(interpreter->literalCache.literals[i]) || IS_TYPE(interpreter->literalCache.literals[i])) {
@@ -1016,4 +1014,7 @@ void runInterpreter(Interpreter* interpreter, unsigned char* bytecode, int lengt
}
execInterpreter(interpreter);
//free the bytecode immediately after use
FREE_ARRAY(unsigned char, interpreter->bytecode, interpreter->length);
}

View File

@@ -301,7 +301,7 @@ void printLiteralCustom(Literal literal, void (printFn)(const char*)) {
void freeLiteral(Literal literal) {
if (IS_STRING(literal)) {
FREE_ARRAY(char, AS_STRING(literal), STRLEN(literal));
FREE_ARRAY(char, AS_STRING(literal), STRLEN(literal) + 1);
return;
}
@@ -315,7 +315,7 @@ void freeLiteral(Literal literal) {
// }
if (IS_IDENTIFIER(literal)) {
FREE_ARRAY(char, AS_IDENTIFIER(literal), STRLEN_I(literal));
FREE_ARRAY(char, AS_IDENTIFIER(literal), STRLEN_I(literal) + 1);
return;
}

View File

@@ -5,7 +5,12 @@
#include <stdio.h>
#include <stdlib.h>
static int allocatedMemoryCount = 0;
void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
allocatedMemoryCount -= oldSize;
allocatedMemoryCount += newSize;
if (newSize == 0) {
free(pointer);
@@ -22,3 +27,6 @@ void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
return mem;
}
int getAllocatedMemoryCount() {
return allocatedMemoryCount;
}

View File

@@ -12,3 +12,4 @@
void* reallocate(void* pointer, size_t oldSize, size_t newSize);
int getAllocatedMemoryCount();

View File

@@ -79,6 +79,8 @@ void freeNode(Node* node) {
freeLiteral(node->increment.identifier);
break;
}
FREE(Node, node);
}
void emitNodeLiteral(Node** nodeHandle, Literal literal) {

View File

@@ -1301,6 +1301,7 @@ Node* scanParser(Parser* parser) {
if (parser->panic) {
synchronize(parser);
//return an error node for this iteration
freeNode(node);
node = ALLOCATE(Node, 1);
node->type = NODE_ERROR;
}

View File

@@ -146,6 +146,10 @@ void repl() {
initInterpreter(&interpreter);
for(;;) {
if (command.verbose) {
//print the used memory footprint
printf("%d ", getAllocatedMemoryCount());
}
printf("> ");
fgets(input, size, stdin);