Receiving "Segmentation fault" when attempting to insert keys in hash table - c

I'm attempting to implement open hashing in C using a linked list struct I've already made. The linked list struct works perfectly, however when trying to use them in my hash table struct, I'm constantly given "Segmentation fault (core dumped)"
I've already checked to make sure that I'm using the proper data types and I'm allocating the right amount of memory.
typedef struct LinkedList LinkedList;
LinkedList* createLinkedList(){
LinkedList* rslt = malloc(sizeof(Node*)); //Allocate memory for LL
//rslt->head = calloc(1,sizeof(Node*)); //Allocate memory for head with default Node* value (NULL)
return rslt;
}
void add_end_LinkedList(LinkedList* x, int v){
//Special case: LinkedList is empty
if(x->head == NULL)
x->head = createNode(v);
else{
//Traversing to end of list
Node* p;
for(p = x->head; p->next != NULL; p = p->next){1;}
p->next = createNode(v);
}
}
void add_beg_LinkedList(LinkedList* x, int v){
Node* p;
//Special case: LinkedList is empty
if(x->head == NULL)
x->head = createNode(v);
else{
p = createNode(v);
p->next = x->head;
x->head = p;
}
}
int isIn_LinkedList(LinkedList* x, int v){
for(Node* p = x->head; p != NULL; p = p->next){
if(p->val == v) return 1;
}
return 0;
}
void print_LinkedList(LinkedList* x){
for(Node* p = x->head; p != NULL; p = p->next){
print_Node(p);
printf(", ");
}
printf("\n");
return;
}
//HASHTABLE_____________________________________________________________
struct HashTable{
LinkedList** table;
};
typedef struct HashTable HashTable;
HashTable* createTable(){
HashTable* rslt = {calloc(9,sizeof(LinkedList*))};
for(int i = 9; i < 9; i++)
rslt->table[i] = createLinkedList();
return rslt;
}
int compute_hash(int v){
return v%9;
}
int isIn_HashTable(HashTable* x, int v){
return isIn_LinkedList(x->table[compute_hash(v)], v);
}
int insert_HashTable(HashTable* x, int v){
if(isIn_HashTable(x, v)){
return 0;
}
add_beg_LinkedList(x -> table[compute_hash(v)], v);
return 1;
}
int main(void){
HashTable* a = createTable();
insert_HashTable(a, 6);
return 0;
}
createTable() does not raise any runtime errors. But any other HashTable functions do. I'm not able to access the linked lists in the table.

Rslt is a pointer. You cannot initialize it the way you initialize struts. After returning from the function the the rslt pointer will become invalid in the following code
HashTable* createTable(){
HashTable* rslt = {calloc(9,sizeof(LinkedList*))};
{..} is not a dynamic memory allocation. Try to malloc rslt first
HashTable *rslt = malloc(sizeof(HashTable));
rslt->table = calloc...

Related

How to initialize struct values and output the struct correctly

I'm attempting some homework and not sure where to go from here, or if I'm on the right path to doing this correctly. This program was given to me with the goal of creating a function to create a new node with an array large enough to hold the input "count". From there I assume I'm supposed to output the created node.
I've tried setting up the node multiple ways with different pointers, I'm not sure how to initialize the 'newnode' correctly though. And every time I try to use the input 'count' such as 'newnode->array_length = count;' I get a segmentation fault, I don't understand why though, if count is input into the function, isn't it usable in the scope of it?
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<assert.h>
typedef struct node {
struct node* previous;
struct node* next;
int array_length;
int* values;
} node;
//creates a new node with an array large enough to hold `count` values
node* create_node(int count) {
//your code here:
node* newnode;
newnode = (node*) malloc(sizeof(node));
newnode->array_length = count;
newnode->values;
newnode->next=NULL;
newnode->previous=NULL;
return newnode;
}
void append(node* a, node* b) {
assert(a);
assert(b);
a->next = b;
b->previous = a;
}
int main() {
node* a = create_node(10);
assert(a->array_length == 10);
assert(a->next == NULL);
assert(a->previous == NULL);
node* b = create_node(20);
assert(b->array_length == 20);
assert(b->next == NULL);
assert(b->previous == NULL);
append(a, b);
assert(a->next == b);
assert(b->previous == a);
assert(a->previous == NULL);
assert(b->next == NULL);
for(node* cur = a; cur != NULL; cur = cur->next) {
for(int i = 0; i < cur->array_length; i++) {
cur->values[i] = i;
}
}
}
Compilation Errors:
problem2.c: In function ‘create_node’:
problem2.c:20:30: warning: implicit declaration of function ‘size’ [-Wimplicit-function-declaration]
newnode->values = malloc(size(int) * count);
^~~~
problem2.c:20:35: error: expected expression before ‘int’
newnode->values = malloc(size(int) * count);
^~~
You're not allocating memory for values. It's set by default to whatever memory was there before, which was probably an invalid pointer. This would cause a segfault when you tried to access values.
//creates a new node with an array large enough to hold `count` values
node* create_node(int count) {
//your code here:
node* newnode = malloc(sizeof(node));
newnode->array_length = count;
newnode->values = malloc(sizeof(int) * count); // malloc memory for values
newnode->next = NULL;
newnode->previous = NULL;
return newnode;
}

how to initializing a hash table in C

I have a program in C that creates a hash table.
memset is Okay but, i want to initialize with for loop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HSZ 127
#define HASHING(x) ((x)%HSZ)
struct node_t{
int val;
struct node_t *next;
};
struct node_t *hash_table[HSZ];
void init(void){
int i;
//memset(hash_table,0,sizeof(hash_table));
for(i=0; i<HSZ; i++){
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}
}
void insert_hash(int value){
int key = HASHING(value);
struct node_t *newNode = (struct node_t*)malloc(sizeof(struct node_t));
newNode->val = value;
newNode->next = NULL;
if(hash_table[key] == NULL){
hash_table[key] = newNode;
} else {
newNode->next = hash_table[key];
hash_table[key] = newNode;
}
}
int delete_hash(int value){
int key = HASHING(value);
if (hash_table[key] == NULL)
return 0;
struct node_t *delNode = NULL;
if (hash_table[key]->val == value){
delNode = hash_table[key];
hash_table[key] = hash_table[key]->next;
} else {
struct node_t *node = &hash_table[key];
struct node_t *next = hash_table[key]->next;
while (next){
if (next->val == value){
node->next = next->next;
delNode = next;
break;
}
node = next;
next = node->next;
}
}
return 1;
free(delNode);
}
void PrintAllHashData()
{
printf("###Print All Hash Data###\n");
for (int i = 0; i < HSZ; i++){
if (hash_table[i] != NULL){
printf("idx : %d ", i);
struct node_t *node = hash_table[i];
while (node->next){
printf("%d ", node->val);
node = node->next;
}
printf("%d\n", node->val);
}
}
}
int main(void){
init();
insert_hash(1);
insert_hash(3);
insert_hash(128);
PrintAllHashData();
}
look at this code.
for(i=0; i<HSZ; i++){
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}
The IDE I am using does not throw up a compilation error when I compile the code, but during the execution the code faults and is terminated/haulted. I tried debugging the code, it faults at this line and is stopped, I think BAD ACCESS points to Segmentation Error.
then, I changed this line to
for(i=0; i<HSZ; i++){
hash_table[i].val = 0;
hash_table[i]->next = NULL;
}
but, then I got the compilation error stating 'structure type require instead of 'struct node_t *'
I think that I don't understand clearly about struct in C.
How to fix this problem?
What you are dealing with is Undefined Behavior.
See, struct node_t *hash_table[HSZ];
So, hash_table is an array of HSZ (127) pointers of the data type struct node_t.
When you do,
for(i=0; i<HSZ; i++){
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}
hash_table[0] to hash_table[126] pointers are not pointing to anything.
So, each of them (or all of them) should be initialized first to point to an object of the type struct node_t and then you can initialize them. For that matter, Using a memset does not cause a problem because memset is filling the contents of the pointers with all zeros. There is difference between filling the pointers with all zeros and filling all zeros to the memory pointed by pointers.
Trying this,
for(i=0; i<HSZ; i++){
hash_table[i].val = 0;
hash_table[i]->next = NULL;
}
is plain wrong.
To fix the issue you are facing, you need to allocate memory dynamically using malloc. You can do the in your for loop.
for(i = 0; i < HSZ; i++)
{
//Allocate memory of the size struct_node_t
hash_table[i] = malloc(sizeof(struct node_t)); //Do not cast!
//Check if memory is allocated
if(hash_table[i] == NULL)
{
//Memory not allocated, set some error state to handle and break
break;
}
//Initialize to zero
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}
struct node_t{
int val;
struct node_t *next;
};
struct node_t *hash_table[HSZ];
when you have *hash_table[HSZ], this varible hash_table is a pointer. so whatever your action is , use hash_table-> ,syntax for pointer, mean point to somewhere.
a suggestion that when you use pointer you should always allocate memory hash_table[i] = malloc(sizeof(struct node_t));
struct node_t hash_table;
but if you initilize your varible like this, you can use hash_table.val = 0
so the way of assign value depend on how you declare your varibles
struct node_t *hash_table[HSZ];
gives you an array of pointers that are unset (i.e. not pointing to anything)
void init(void) {
int i;
// memset(hash_table,0,sizeof(hash_table));
for (i = 0; i < HSZ; i++) {
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
tries writing to your invalid pointers which gives undefined behavior.
Either make the array an array of structs (instead of pointers):
struct node_t hash_table[HSZ];
...
/* note use of . instead of -> since we have structs not pointers */
hash_table[i].val = 0;
or allocate the necessary structs so the array points to something:
for (i = 0; i < HSZ; i++) {
hash_table[i] = malloc(sizeof(struct node_t));
hash_table[i]->val = 0;
hash_table[i]->next = NULL;
}

What is wrong in this code for graph?

#include<stdio.h>
struct llist {
int data;
struct llist *next;
};
typedef struct llist list;
struct graph {
int V;
list **adj;
};
typedef struct graph graph;
graph* create_graph(int V) {
list **adj = (list**)malloc(sizeof(list*)*V);
graph *a = (graph*)malloc(sizeof(graph));
a->V = V;
a->adj = adj;
return a;
}
void insert_list(list **head, int v) {
list *new_node, *temp_node, *last_node;
new_node = (list*)malloc(sizeof(list));
new_node->data = v;
new_node->next = NULL;
printf("\n hi %d", head);
/*
* head is empty, point the head to temp and return.
*/
if (*head == NULL) {
*head = new_node;
return;
}
temp_node = *head;
do{
last_node = temp_node;
temp_node = temp_node->next;
}while(temp_node);
last_node->next = new_node;
}
void addedge(graph *g, int u, int v) {
insert_list(&(g->adj[u]), v);
}
int
main() {
int V = 10;
graph *a = create_graph(V);
printf("\n graph created");
addedge(a, 1,2);
addedge(a,1,5);
addedge(a,2,1);
addedge(a,2,5);
addedge(a,2,3);
addedge(a,2,4);
addedge(a,3,2);
addedge(a,3,4);
addedge(a,4,2);
addedge(a,4,5);
addedge(a,4,3);
addedge(a,5,4);
addedge(a,5,1);
addedge(a,5,2);
return 0;
}
In this code, by printing messages, I have found is create_graph function executes properly and returns a graph. Then addedge is being called, In it, if(*head==NULL) part always returns false (Don't know why, first time it should return true). Then it goes ahead in do while loop and that keep executing till infinity and code terminates.
What I am trying to do is I have a structure called graph, with a integer variable V and array of linked list variable adj (represents adjacency list). And then create graph will initialise a graph variable and return it.
Addedge(V,u,v) will add edge v to u (means v is adjacent to u). so adj[0....V-1] is a array of linked list. so if edge 1 is adjacent to 2 and 3, then list will look like 1->2->3.
Comment If more info needed. I don't know what why *head is not null the first time and why the while loop never terminates.
Thanks a lot in advance.
By trail and error, I found the mistake.
In function create graph, after initialising the list, each individual list also must be initialised to NUll, otherwise it will have junk stuff.
Below is correct code :
graph* create_graph(int V) {
list **adj = (list**)malloc(sizeof(list*)*V);
int i;
for (i = 0; i < V; ++i) {
adj[i] = NULL;
}
graph *a = (graph*)malloc(sizeof(graph));
a->V = V;
a->adj = adj;
return a;
}

Sequence insert at arbitrary index implemented with Linked list

I'm trying to implement sequence_insert_at using the add_to_front function here
Everything before
typedef struct sequence *Sequence;
is pasted from another c file.
void sequence_insert_at(Sequence s, int pos, int item)
{
struct node* temp = s->lst;
for(; pos > 0; --pos)
{
temp = temp->rest;
}
add_to_front(&temp, item);
++s->length;
if(!temp->rest)
{
s->end = temp;
}
//s->lst = temp;
}
I don't know why I keep getting a runtime error. if I clone s->lst and traverse the clone, I'm not modifying the pointer to the node in s, but if I change temp, s->lst should have the reflected changes since the nodes are all linked still. Any ideas as to how to fix this? I tried creating another node that is one before the temp after traversal, and then setting it->rest = temp, but that failed as well.
following mistakes a could spot but only so far to get the main function run
new_sequence does not initialize anything in Sequence it creates. lst is not initialized when you access it in sequence_insert_at
struct node* temp = s->lst;
here how it should look like
Sequence new_sequence()
{
Sequence s = malloc(sizeof(struct sequence));
if(!s)
{
printf("Out of memory. Can't allocate s\n");
exit(EXIT_FAILURE);
}
s->lst = malloc(sizeof(struct node));
if(! s->lst) {
printf("Out of memory. Can't allocate lst\n");
}
s->lst->rest = NULL;
s->length = 0;
return s;
}
also s->lst->rest has to be set to NULL, this is what tells that the list has no more elements an not end witch turns obsolete.
struct sequence
{
struct node* lst;
int length;
};
You should be passing the sequence itself to your functions not a pointer to some internal data in the sequence.
add_to_front(&temp, item);
Your sequence_insert_at function should be the one that can handle any position not add_to_front() so it is easier to call with the position 0 from add_to_front() and your having the the hole work done in one function, not a half here and a half there.
void sequence_insert_at(Sequence s, int pos, int item)
{
if(s && pos <= s->length) {
print_sequence(s);
struct node *newnode = malloc(sizeof(struct node));
if (newnode == NULL) {
printf("ERROR! add_to_front ran out of memory!\n");
exit(EXIT_FAILURE);
}
newnode->first = item;
struct node* temp = s->lst;
struct node* prv = NULL;
for(int i = 0; i < pos; i++) {
printf("skip %d\n", temp->first);
prv = temp;
temp = temp->rest;
}
newnode->rest = temp;
if(pos == 0) {
printf("insert as first\n");
s->lst = newnode;
} else {
printf("insert before %d\n", temp->first);
prv->rest = newnode;
}
++s->length;
}
}
and in add_to_front only one statement is needed
void add_to_front(Sequence s, int item) {
sequence_insert_at(s, 0, item);
}
as for inserting at the back of the list
void add_to_back(Sequence s, int item) {
sequence_insert_at(s, s->length, item);
}
A small test with the main function
void print_sequence(Sequence s)
{
struct node* temp = s->lst;
for(int i = 0; i < s->length; temp = temp->rest) {
printf("%d ", temp->first);
i++;
}
printf("\n");
}
int main()
{
Sequence derp = new_sequence();
sequence_insert_at(derp, 0, 14);
add_to_front(derp, 16);
sequence_insert_at(derp, 0, 17);
sequence_insert_at(derp, 2, 15);
add_to_back(derp, 13);
print_sequence(derp);
delete_sequence(derp);
return 0;
}
output is:
17 16 15 14 13
You'll have to go trough the other functions and fix them.
Finally i should note that variable names you have choosen are little bit confusing if not misleading, i would name them this way
typedef struct node {
int data; /* the data that a node holds */
struct node* next; /* the pointer to the next node */
} Node_t;
typedef struct sequence {
struct node* head; /* head or first element of the sequence/list */
int length; /* length is ok but size is better */
} Sequence_t;

C - pointer to struct to array of pointers

I have a linked list with a hash table in each node. The hash table is implemented by an array of pointers to structs. The whole management of this is made by a global static pointer to the linked list.
I changed a little bit the question! Now the question is more focused.
in the lookup and insert function to make the code shorter I assign
temp = cur_table->symbols_table[entry];
but I see that temp gets NULL all the time.
I can't understand why is that happens?
The code is below in 3 modules.
Thank you in ahead.
symbols.h file:
#include <stdlib.h>
#include <stdio.h>
#define TABLE_SIZE 26
typedef struct symbol_node
{
char* name;
int type;
int role;
struct symbol_node* next;
} symbol_node;
typedef struct table_node
{
struct symbol_node* symbols_table[TABLE_SIZE];
struct table_node* prev;
struct table_node* next;
} table_node;
static struct table_node* cur_table;
//functions declarations:
void init_table();
int hash_function(char* id);
symbol_node* lookup(char* id_name);
symbol_node* insert(char* id_name);
// debug
void printtable();
symbols.c
void init_table() // creates the first node
{
int i = 0;
cur_table = NULL;
cur_table = (table_node*)malloc(sizeof(table_node));
cur_table->prev = NULL;
cur_table->next = NULL;
for(i=0; i < TABLE_SIZE; i++)
{
cur_table->symbols_table[i] = NULL;
}
}
symbol_node* lookup(char* id_name) // returns null if the id name not found
{
symbol_node* result = NULL;
symbol_node* temp = NULL;
int entry = atoi(id_name);
temp = cur_table->symbols_table[entry];
while(temp != NULL)
{
if( strcmp( id_name, temp->name ) == 0 )
{
result = temp;
break;
}
else
temp = temp->next;
}
return result;
}
symbol_node* insert(char* id_name)
{
symbol_node* result = NULL;
symbol_node* temp = NULL;
int index = -1;
if(lookup(id_name)==NULL)
{
index = atoi(id_name);
temp = cur_table->symbols_table[index];
while(temp!=NULL)
{
temp = temp->next;
}
temp = (symbol_node*)malloc(sizeof(symbol_node));
temp->next = NULL;
temp->name = id_name;
// TODO: other params
result = temp;
}
return result;
}
void printtable()
{
int i=0;
for(i=0; i<TABLE_SIZE; i++)
{
if(cur_table->symbols_table[i]==NULL)
printf("NULL at index %d\n",i);
else
printf("There are something\n");
}
}
main.c
void main()
{
int i=0;
symbol_node* t = NULL;
symbol_node* tt = NULL;
init_table();
t = insert("markhit");
t = insert("mark");
tt = lookup("mark");
printtable();
_getch();
free(t);
free(tt);
free(cur_table);
}
avoid memory allocation [`malloc'] statically. try it
cur_table = new table_node;
for statically allocated memory, you can not set your value for memory reason. when you are inserting it is not reallocating your cur_table

Resources