There's a very interesting github repo called "build-your-own-x": https://github.com/codecrafters-io/build-your-own-x
I'm trying out building my own hash table in C
Step 1: Hash Table Structure
// hash_table.h
typedef struct {
const char* key;
void* value;
} item;
typedef struct {
item** items;
int size;
int count;
} hash_table;
// hash_table.c
#include <stdlib.h>
#include <string.h>
#include "hash_table.h"
#define INITIAL_CAPACITY 10
item* create_item(const char* key, void* value) {
item* i = malloc(sizeof(item));
i->key = strdup(key);
i->value = value;
return i;
}
void free_item(item* i) {
free((void*)i->key);
free(i->value);
free(i);
}
hash_table* create_ht() {
hash_table* ht = malloc(sizeof(hash_table));
ht->size = INITIAL_CAPACITY;
ht->count = 0;
ht->items = calloc(ht->size, sizeof(item*));
return ht;
}
void free_ht(hash_table* ht) {
for (int i=0; i<ht->size; ++i) {
item* item = ht->items[i];
if (item != NULL) {
free_item(ht->items[i]);
}
}
free(ht->items);
free(ht);
}
int main(int argc, char** argv) {
hash_table* ht = create_ht();
free_ht(ht);
}
I encountered a segment fault with my initial version where I didn't check if item is NULL:
void free_ht(hash_table* ht) {
for (int i=0; i<ht->size; ++i) {
free_item(ht->items[i]);
}
free(ht->items);
free(ht);
}
I debugged using lldb:
cc -std=c99 -Wall hash_table.c -g -o hash_table
lldb hash_table
(lldb) target create "hash_table"
Current executable set to 'hashmap/hash_table' (arm64).
(lldb) run
Process 32574 launched: 'hashmap/hash_table' (arm64)
Process 32574 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
frame #0: 0x0000000100003e54 hash_table`free_item(i=0x0000000000000000) at hash_table.c:17:20
14 }
15
16 void free_item(item* i) {
-> 17 free((void*)i->key);
18 free(i->value);
19 free(i);
20 }
(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
* frame #0: 0x0000000100003e54 hash_table`free_item(i=0x0000000000000000) at hash_table.c:17:20
frame #1: 0x0000000100003f20 hash_table`free_ht(ht=0x0000000126e05bf0) at hash_table.c:33:9
frame #2: 0x0000000100003f78 hash_table`main(argc=1, argv=0x000000016fdff0d8) at hash_table.c:42:3
frame #3: 0x000000018f3e90e0 dyld`start + 2360
(lldb) f 0
frame #0: 0x0000000100003e54 hash_table`free_item(i=0x0000000000000000) at hash_table.c:17:20
14 }
15
16 void free_item(item* i) {
-> 17 free((void*)i->key);
18 free(i->value);
19 free(i);
20 }
(lldb) v
(item *) i = NULL
When running "bt" to check call stack, it becomes very obvious the segment fault happened in main()->free_ht()->free_item();
I then ran "f 0" to check frame #0 where the function causing the segment fault is. Then I ran "v" to check what variables are there.
The it becomes very clear i = NULL which is causing the issue. After adding a NULL check and compile and run again, the segment faults is gone.