Please keep in mind I am new to C and the whole pointers/memory allocation is a bit tricky to me. Also so is the command line argument input through the terminal.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node {
long long key;
long long val;
struct node *next;
};
struct hashTable {
struct node *head;
int buckets;
};
int count = 0;
struct hashTable *newTable;
//create a new node
struct node * createNode (long long key, long long val) {
struct node *newNode;
newNode = (struct node *) malloc(sizeof(struct node));
newNode -> key = key;
newNode -> val = val;
newNode -> next = NULL;
return newNode;
}
//insert data into Hash
void insertToHash(long long key, long long val) {
// hash func
int hashIndex = key % 1000, inTable = 0;
struct node *newNode = createNode(key, val);
//traversal nodes
struct node *temp, *curr;
curr = newTable[hashIndex].head;
//if the table at given index is empty
if (newTable[hashIndex].head == NULL) {
newTable[hashIndex].head = newNode;
count ++;
return;
}
temp = curr;
//if key is found break, else traverse till end
while(curr != NULL) {
if (curr -> key == key) {
inTable = 1;
free(newNode); //since already in the able free its memory
break;
}
else {
temp = curr;
curr = curr->next;
}
}
if (inTable == 1) {
printf("Address is already in the table");
}
//key not found so make newNode the head
else {
newNode -> next = newTable[hashIndex].head;
newTable[hashIndex].head = newNode;
count ++;
}
}
//initialize hashtable to 1000 entries
struct hashTable * createHashTable (int buckets) {
int i;
for(i=0; i<buckets; i++) {
newTable[i].head = NULL;
}
return newTable;
}
int main(int argc, char *argv[]) {
createHashTable(1000);
}
So when I searched up what a Segmentation Fault 11 was I found out that it has to do with not having access to certain memory. I'm assuming my issue has something to do with initializing the table newTable and not using pointers properly or allocating memory for it properly. Please keep in mind this is my first real attempt to create a data structure in C so things that might seem obvious aren't obvious to me.