I have a big project in C that has somewhere around 2 thousand lines of code.
I have in this project a linked list that I am using to store data of the program, at the end of the program I am calling a function I wrote to free the memory of the linked list. but for some reason I am getting this error:
free(): invalid pointerAborted (code dumped)
I have my linked list seperated in its own header file so it doesn't matter where in my code I am adding nodes to that lists they all just called insertSymbol
to insert new list so I know what the nodes are allocated in the heap memory.
Can someone tell me what is wrong with the way I am doing this and also explain to me why does it happens??
this is my SymbolTable.h file
#ifndef SYMBOL_TABLE_H#define SYMBOL_TABLE_H#include <stdio.h>#include <stdlib.h>#include <string.h>#include "constants.h"/** * a struct holding the SymbolTable information*/typedef struct SymbolTable { char* symbol; unsigned int identifier:2; int value; struct SymbolTable *next;} SymbolTable;extern SymbolTable* symbol_table;/** * Function insertSymbol * --------------------- * gets the symbol information (e.g. symbol name, identefier and value) * and insert it to the symbol table * * @param symbol: string holding the symbol name * @param identerfier: an integer holding the id of the symbol (e.g. .code, .mdefine or .data) * @param value: the value of the symbol in the memory*/void insertSymbol(const char* symbol, const int identifier, const int value);/** * Function lookupSymbol * ---------------------- * searching a symbol in the symbol table * * @param symbol: a string holding the symbol name to search * * @return a pointer to the symbol matching the name passed as an argument*/SymbolTable* lookupSymbol(const char* symbol);/** * Function freeSymbolTable * ------------------------ * releasing the memory that was allocated to the symbol_table data structure*/void freeSymbolTable();#endif
and this is the source code for it:
#include "../headers/symbolTable.h"SymbolTable* symbol_table = NULL;void insertSymbol(const char *symbol, const int identifier, const int value){ SymbolTable **temp = &symbol_table; while (*temp != NULL) { temp = &(*temp)->next; } *temp = (SymbolTable*)calloc(1, sizeof(SymbolTable)); (*temp)->symbol = (char*)calloc(strlen(symbol) + 1, sizeof(char)); strcpy((*temp)->symbol, symbol); (*temp)->identifier = identifier; (*temp)->value = value; (*temp)->next = NULL;}SymbolTable* lookupSymbol(const char *symbol){ SymbolTable *temp = symbol_table; /* iterating over the symbol table and returning a pointer to the symbol if it was found otherwise returning null */ while (temp != NULL) { if (strcmp(temp->symbol, symbol) == 0) { return temp; } temp = temp->next; } return NULL;}void freeSymbolTable(){ /* iterating over the symbol table and releasing the memory that was allocated for it */ SymbolTable *temp = NULL; while (symbol_table != NULL) { temp = symbol_table; symbol_table = symbol_table->next; free(temp); temp = NULL; }}