Integer is 0 after being retrieved from C struct - c

I'm failing to see why the messageSize is printing 0 when calling removeNode, especially since it has no problem getting and printing the message. The printf in insertNode is printing the size correctly. This might just be a simple oversight. Not sure.
struct qnode {
char message[256];
int mesglen;
struct qnode * next;
};
struct qheader {
struct qnode * front;
struct qnode * last;
};
struct qheader queue;
void insertNode() {
struct qnode newnode;
char * buffer = "hello";
strcpy(newnode.message, buffer);
printf("insert size: %ld\n", strlen(buffer)); // 5
newnode.mesglen = (int)strlen(buffer);
struct qnode * curnode = queue.front;
if (curnode == NULL) {
queue.front = &newnode;
queue.last = &newnode;
} else {
while (curnode->next != NULL) {
curnode = curnode->next;
}
curnode->next = &newnode;
queue.last = &newnode;
}
}
void removeNode() {
char message[256] = {0};
int messageSize;
if (queue.front == NULL) {
printf("queue empty\n");
} else {
strcpy(message, queue.front->message);
messageSize = queue.front->mesglen;
queue.front = queue.front->next;
printf("MESSAGE: %s\n", message);
printf("MESSAGESIZE: %d\n", messageSize);
}
}
int main() {
insertNode();
removeNode();
return 0;
}
And the output:
insert size: 5
MESSAGE: hello
MESSAGESIZE: 0

Related

Program received signal SIGSEGV, Segmentation fault when asking user input for doubly linked list

I am new to C programming and When I asked user to input a number for some reason my whole program gives this error
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555753 in addData (word=0x7fffffffeb70 "", mode=2) at main.c:202
202 if (temp->next == NULL) {
(gdb)
HERE IS MY CODE
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define MEMORY 6
#define MAX_word_LENGTH 11
int numberOfwords;
char words[MEMORY][MAX_word_LENGTH];
struct Node{
int data;
char *word;
struct Node *next, *prev;
};
struct Node *head, *tail;
struct Node* DlListDeleteLastNode(struct Node *head);
void addData(char *word, int mode);
void DisplayForward();
struct Node* deletePos(struct Node *head, int pos);
int getPostion(char *targetWord);
bool search(char *targetWord);
//struct Node* deletePos(struct Node *head, int pos);
int countWord(char *wording);
void insert_specified(char *wording, int pos);
int countNodes();
//void init(){
// head = NULL;
// tail = NULL;
//}
int main()
{
char name[100];
//char searchName[] = "barr";
printf("Enter number of words to be stored in the word stream: ");
int input;
scanf("%d", &input);
int i;
int count = 0;
for (i=0; i<input;i++){
count++;
printf("\nEnter name %d : ",count);
scanf ("%[^\n]%*c", name);
//scanf("%s[^\n]",words[i]);
addData(name, 2);
}
//for (int i = 0; i <4; i++) {
// strcpy(words[i],
//}
//insert_specified(searchName, 0);
//printf("%d\n", numberOfwords);
//DlListDeleteLastNode();
DisplayForward();
//int num = countNodes();
//printf("count %d", num);
//deletePos(head, 3);
//bool x = search(searchName);
//printf("%d\n", x);
//printf("%d\n", numberOfwords);
//DisplayForward();
//fflush(stdin);
printf("\nEntered names are:\n");
for(i=0;i<6;i++)
puts(words[i]);
}
int isEmpty(struct Node *h){
if(h==NULL)
return 1;
else
return 0;
}
void addData(char *word, int mode){
if (mode == 1) {
for (int i=0; i<5; i++) {
if (strcmp(words[i],word) == 0) {
//printf("found\n");
//printf("FOUND%s\n", word);
int x = getPostion(word);
//printf("index found %d/n", x);
//deletePos(head, x);
struct Node* temp = head;
struct Node* temp2 = NULL;
while (x > 1) {
temp = temp->next;
x--;
}
if (temp->next == NULL) {
head = DlListDeleteLastNode(head);
}
else {
temp2 = temp->prev;
temp2->next = temp->next;
temp->next->prev = temp2;
free(temp);
temp = NULL;
}
break;
}
//x index = getPostion()
}
if (numberOfwords >= 5) {
DlListDeleteLastNode(head);
struct Node *ptr;
ptr= malloc(sizeof *ptr);
ptr->word = malloc(sizeof(char) * 12);
//char nimI[20];
//baru->nim = malloc(12 * sizeof(char));
//strcpy(ptr->word, word);
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
strcpy(ptr->word, word);
//ptr->word= word;
head=ptr;
//head = ptr;
//tail = ptr;
}
else
{
//ptr->word=word;
strcpy(ptr->word, word);
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
numberOfwords++;
}
else {
struct Node *ptr;
ptr= malloc(sizeof *ptr);
ptr->word = malloc(sizeof(char) * 12);
//char nimI[20];
//baru->nim = malloc(12 * sizeof(char));
//strcpy(ptr->word, word);
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
strcpy(ptr->word, word);
//ptr->word= word;
head=ptr;
//head = ptr;
//tail = ptr;
}
else
{
//ptr->word=word;
strcpy(ptr->word, word);
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
numberOfwords++;
strcpy(words[numberOfwords], word);
}
}
else {
int flag = 0;
//int numWords = countNodes();
for (int i=0; i<8; i++) {
if (strcmp(words[i],word) == 0) {
//printf("found\n");
//printf("FOUND%s\n", word);
int x = getPostion(word);
//printf("index found %d/n", x);
//deletePos(head, x); //
struct Node* temp = head;
struct Node* temp2 = NULL;
while (x > 1) {
temp = temp->next;
x--;
}
if (temp->next == NULL) {
head = DlListDeleteLastNode(head);
}
else {
temp2 = temp->prev;
temp2->next = temp->next;
temp->next->prev = temp2;
free(temp);
temp = NULL;
}
flag = 1;
//DisplayForward();
//numberOfwords--;
break;
}
//x index = getPostion()
}
printf("\nflag num-> %d\n", flag);
//numberOfwords++;
int numWords = countNodes();
if (numWords >= 5 && flag==0) {
//printf("activated");
int max = 0;
char maxWord[50];
for (int i = 0; i < 8; i++) {
int num = countWord(words[i]);
if (num > max) {
max = num;
//printf("%d", max);
strcpy(maxWord, words[i]);
//printf("word %s\n", maxWord);
}
}
printf("most occured word: %s\n", maxWord);
int mostOccuredWordIndex = getPostion(maxWord);
printf("index: %d\n", mostOccuredWordIndex);
mostOccuredWordIndex--;
insert_specified(word, mostOccuredWordIndex);
DlListDeleteLastNode(head);
}
else if (numWords >= 5) {
//DlListDeleteLastNode(head);
//struct Node *ptr;
//ptr= malloc(sizeof *ptr);
//ptr->word = malloc(sizeof(char) * 12);
//char nimI[20];
//baru->nim = malloc(12 * sizeof(char));
//strcpy(ptr->word, word);
//Get most occured word in words array
//find the position of the most occured word
//int mostOccuredWordIndex = getPostion(maxWord);
//remove last element and insert new word into that position
//if position is in the last index then remove word and replace with the word
//if (mostOccuredWordIndex == 5) {
// printf("occurred");
//}
//
DlListDeleteLastNode(head);
numberOfwords = numberOfwords + 1;
struct Node *ptr;
ptr= malloc(sizeof *ptr);
ptr->word = malloc(sizeof(char) * 12);
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
strcpy(ptr->word, word);
//ptr->word= word;
head=ptr;
//head = ptr;
//tail = ptr;
}
else
{
//ptr->word=word;
strcpy(ptr->word, word);
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
}
else {
struct Node *ptr;
ptr= malloc(sizeof *ptr);
ptr->word = malloc(sizeof(char) * 12);
//char nimI[20];
//baru->nim = malloc(12 * sizeof(char));
//strcpy(ptr->word, word);
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
strcpy(ptr->word, word);
//ptr->word= word;
head=ptr;
//head = ptr;
//tail = ptr;
}
else
{
//ptr->word=word;
strcpy(ptr->word, word);
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
numberOfwords = numberOfwords + 1;
strcpy(words[numberOfwords], word);
}
DisplayForward();
numWords = countNodes();
printf("\nnumber of words%d \n", numWords);
}
}
struct Node* DlListDeleteLastNode(struct Node *head) {
struct Node *temp = head;
struct Node* temp2;
while (temp->next != NULL) {
temp = temp->next;
}
temp2 = temp->prev;
temp2->next = NULL;
free(temp);
numberOfwords--;
return head;
}
void DisplayForward() {
//Node current will point to head
struct Node *current = head;
if(head == NULL) {
printf("List is empty\n");
return;
}
printf("[");
int count = numberOfwords;
// while current->next != Null
while(current!=NULL) {
//Prints each node by incrementing pointer.
printf("%s, ", current->word);
current = current->next;
count--;
}
//current = current->next;
//printf("%s]\n", current->word);
//printf("%d", numberOfwords);
}
bool search(char *targetWord) {
int pos = 0;
if(head==NULL) {
printf("Linked List not initialized");
return;
}
struct Node *current = head;
//current = head;
while(current!=NULL) {
pos++;
if(strcmp(current->word, targetWord) == 0) {
printf("%s found at position %d\n", targetWord, pos);
return true;
}
if(current->next != NULL)
current = current->next;
else
break;
}
return false;
//printf("%s does not exist in the list\n", targetWord);
}
int getPostion(char *targetWord) {
int pos = 0;
if(head==NULL) {
printf("Linked List not initialized");
return -1;
}
struct Node *current = head;
//current = head;
while(current!=NULL) {
pos++;
if(strcmp(current->word, targetWord) == 0) {
//printf("%s found at position %d\n", targetWord, pos);
return pos;
}
if(current->next != NULL)
current = current->next;
else
break;
}
return -1;
//printf("%s does not exist in the list\n", targetWord);
}
int countWord(char *wording) {
int count = 0;
for(int i=0;i<6;i++) {
if (strcmp(words[i], wording)==0) {
//printf("found word");
count++;
}
}
return count;
}
void insert_specified(char * wording, int pos)
{
struct Node *ptr;
ptr= malloc(sizeof *ptr);
ptr->word = malloc(sizeof(char) * 12);
struct Node *temp;
int i;
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
//printf("\nEnter the location\n");
//scanf("%d",&loc);
temp=head;
for(i=0;i<pos;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
}
}
strcpy(ptr->word, wording);
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("Node Inserted\n");
}
}
int countNodes() {
int counter = 0;
//Node current will point to head
struct Node *current = head;
while(current != NULL) {
//Increment the counter by 1 for each node
counter++;
current = current->next;
}
return counter;
}
I tried to ask the user for a number of words it wants to input for my program to store the items in a doubly linked list but instead gives a segmentation fault error
struct Node *head is a global variable which is zero initialized. In addData() you set struct Node* temp = head; and then you deference temp like your stack trace shows which will segfault.
Anyways, before you even get there the 2nd scanf() fails as it the input buffer contains the \n from reading the previous number. The syntax of the format string also looks wrong to me. In any case as you don't check the return value of you are operating on uninitialized data. Here is the minimal fix:
if(scanf(" %99[^\n]*", name) != 1) {
printf("scanf failed\n");
return 1;
}
I also replaced the hard-coded < 8 with < MEMORY to avoid a buffer overflow. Here is an example run:
Enter number of words to be stored in the word stream: 2
Enter name 1 : test
flag num-> 0
[test,
number of words1
Enter name 2 : test2
flag num-> 0
[test2, test,
number of words2
[test2, test,
Entered names are:
test
test2

Receive SIGSEGV in _IO_vfscanf_internal()

My program will compile and run normally, however, when I run the program through GDB, I receive a SIGSEGV, Segmentation fault
(0x0000003ec945352f in _IO_vfscanf_internal () from /lib64/libc.so.6)
after the fscanf in my code fills a node of a linked list. What causes the segmentation fault in GDB but not when I run my program?
(gdb) s
90 fscanf(fp,"%s %s %d %d", newNode->record_->first_name_, newNode->record_->last_name_, &newNode->record_->student_id_, &newNode->record_->student_age_);
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x0000003ec945352f in _IO_vfscanf_internal () from /lib64/libc.so.6
#include <stdio.h>
#include <stdlib.h>
struct student_record_node
{
struct student_record* record_;
struct student_record_node* next_;
};
struct student_record
{
int student_id_;
int student_age_;
char first_name_[21];
char last_name_[21];
};
void parseFile();
struct student_record_node* student_record_allocate();
void appendNode(struct student_record_node* head, struct student_record_node* newNode);
void printNode(struct student_record_node* node);
void student_record_node_deallocate(struct student_record_node* node);
void printNodeList(struct student_record_node* head);
void swap(struct student_record_node** node1, struct student_record_node** node2);
void sortByAge(struct student_record_node** recordsHead);
void sortById(struct student_record_node** recordsHead);
void freeNodeList(struct student_record_node* head);
void student_record_node_deallocate(struct student_record_node* node);
int main(int argc, char* argv[])
{
struct student_record_node* node = student_record_allocate();
struct student_record_node** head = &node;
parseFile(argv[1], head);
printf("Before sorting...\n");
printNodeList(*head);
sortByAge(head);
printf("Sorting by age...\n");
printNodeList(*head);
sortById(head);
printf("Sorting by id...\n");
printNodeList(*head);
freeNodeList(*head);
}
struct student_record_node* student_record_allocate()
{
struct student_record_node* newNode;
newNode = calloc(1, sizeof(struct student_record_node));
if (newNode == NULL)
{
printf("No memory allocated for newNode");
exit(1);
}
newNode->record_ = calloc(1, sizeof(struct student_record));
if (newNode->record_ == NULL)
{
printf("No memory allocated for record_");
exit(1);
}
newNode->next_ = NULL;
return newNode;
}
void parseFile(char* filename, struct student_record_node** head)
{
int i = 0;
struct student_record_node* newNode = *head;
FILE* fp;
fp = fopen(filename,"r");
if (fp == NULL)
{
printf("Could not read file\n");
exit(1);
}
while(1)
{
if(newNode != *head)
{
newNode = student_record_allocate();
appendNode(*head, newNode);
}
fscanf(fp,"%s %s %d %d", newNode->record_->first_name_, newNode->record_->last_name_, &newNode->record_->student_id_, &newNode->record_->student_age_);
if(newNode == *head)
{
newNode = NULL;
}
if(feof(fp))
{
break;
}
}
fclose(fp);
}
void appendNode(struct student_record_node* head, struct student_record_node* newNode)
{
int i = 1;
struct student_record_node* current = head;
while (i)
{
if (current->next_ == NULL)
{
current->next_ = newNode;
i = 0;
}
current = current->next_;
}
}
void printNode(struct student_record_node* node)
{
printf("struct student_record_node:\n");
printf("\tStudent first name: %s\n", node->record_->first_name_);
printf("\tStudent last name: %s\n", node->record_->last_name_);
printf("\tStudent id: %d\n", node->record_->student_id_);
printf("\tStudent age: %d\n", node->record_->student_age_);
}
void printNodeList(struct student_record_node* head)
{
struct student_record_node* current = head;
while (current->next_ != NULL)
{
printNode(current);
current = current->next_;
}
printf("\n");
}
void swap(struct student_record_node** node1, struct student_record_node** node2)
{
struct student_record* newNode;
struct student_record_node* big = *node2;
struct student_record_node* small = *node1;
newNode = big->record_;
big->record_ = small->record_;
small->record_ = newNode;
}
void sortByAge(struct student_record_node** recordsHead)
{
int i,j;
struct student_record_node* current = *recordsHead;
struct student_record_node* next = *recordsHead;
while (current->next_->next_ != NULL)
{
next = current;
while (next->next_->next_ != NULL)
{
if (next->next_->record_->student_age_ <= next->record_->student_age_)
{
swap(&next->next_, &next );
}
next = next->next_;
}
current = current->next_;
}
}
void sortById(struct student_record_node** recordsHead)
{
int i = 0;
struct student_record_node* current = *recordsHead;
struct student_record_node* beginning = *recordsHead;
struct student_record_node* next = *recordsHead;
while (current->next_->next_ != NULL)
{
next = beginning;
while(next->next_->next_ !=NULL)
{
if (next->next_->record_->student_id_ <= next->record_->student_id_)
{
swap(&next->next_, &next);
}
next = next->next_;
}
current = current->next_;
}
}
void student_record_node_deallocate(struct student_record_node* node)
{
struct student_record_node* tmp;
tmp = node;
free(tmp->record_);
free(tmp);
}
void freeNodeList(struct student_record_node* head)
{
while (head != NULL)
{
student_record_node_deallocate(head);
head = head->next_;
}
}

Linked list add() method in C

Where is error the following code?
addNode() function is not run, neither is the traverse() function.
Last data is not shown.
#include <stdio.h>
#include <stdlib.h>
struct isimler{
char isim[10];
struct isimler *next;
};
typedef struct isimler node;
node *head;
void createList(){
int k, n;
node *po;
printf("Eleman Sayisi: "); scanf("%d", &n);
for(k = 0; k<n; k++){
if(k == 0){
head = (node *) malloc(sizeof(node));
po = head;
}else{
po->next = (node *) malloc(sizeof(node));
po = po->next;
}
printf("Isim Girin: "); scanf("%s",po->isim);
}
po->next = NULL;
}
void addNode(){
node *po, *newNode;
po = head;
while(po != NULL){
po = po->next;
}
po = (node *) malloc(sizeof(node));
printf("Isim Girin: "); scanf("%s", po->isim);
po->next = NULL;
}
void traverseList(){
node *po;
int i=0;
po = head;
while(po != NULL){
printf("%d.\t%s\n",i,po->isim);
po = po->next;
i++;
}
}
int main(){
createList();
traverseList();
addNode();
traverseList();
return 1903;
}
Your current addNode() method creates a new node but it doesn't add it to your linked list.
You need to modify your addNode() method like so:
void addNode(){
node *po, *newNode;
po = head;
while(po->next != NULL) { // change this so you don't lose the end of the list
po = po->next; // po is now pointing to the last node in the list
}
newNode = (node *) malloc(sizeof(node)); // change this to newNode
printf("Isim Girin: "); scanf("%s", newNode->isim);
po->next = newNode; // add the new node here, don't set it to NULL
newNode->next = NULL;
}
You can have look this code and get to know where exactly you are having problem
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct test_struct
{
int val;
struct test_struct *next;
};
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int val)
{
printf("\n creating list with headnode as [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
head = curr = ptr;
return ptr;
}
struct test_struct* add_to_list(int val, bool add_to_end)
{
if(NULL == head)
{
return (create_list(val));
}
if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else
printf("\n Adding node to beginning of list with value [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
if(add_to_end)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}
return ptr;
}
struct test_struct* search_in_list(int val, struct test_struct **prev)
{
struct test_struct *ptr = head;
struct test_struct *tmp = NULL;
bool found = false;
printf("\n Searching the list for value [%d] \n",val);
while(ptr != NULL)
{
if(ptr->val == val)
{
found = true;
break;
}
else
{
tmp = ptr;
ptr = ptr->next;
}
}
if(true == found)
{
if(prev)
*prev = tmp;
return ptr;
}
else
{
return NULL;
}
}
int delete_from_list(int val)
{
struct test_struct *prev = NULL;
struct test_struct *del = NULL;
printf("\n Deleting value [%d] from list\n",val);
del = search_in_list(val,&prev);
if(del == NULL)
{
return -1;
}
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{
curr = prev;
}
else if(del == head)
{
head = del->next;
}
}
free(del);
del = NULL;
return 0;
}
void print_list(void)
{
struct test_struct *ptr = head;
printf("\n -------Printing list Start------- \n");
while(ptr != NULL)
{
printf("\n [%d] \n",ptr->val);
ptr = ptr->next;
}
printf("\n -------Printing list End------- \n");
return;
}
int main(void)
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
for(i = 5; i<10; i++)
add_to_list(i,true);
print_list();
for(i = 4; i>0; i--)
add_to_list(i,false);
print_list();
for(i = 1; i<10; i += 4)
{
ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val);
}
print_list();
ret = delete_from_list(i);
if(ret != 0)
{
printf("\n delete [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n delete [val = %d] passed \n",i);
}
print_list();
}
return 0;
}

Inserting and Removing from Linked List

This is a hashtable implementation.
I have the insert kinda working but how do I return the linked list?
I know that the remove is not done yet but I understand the concept, my problem is returning the adjusted list.
I tried to make the hashtable a global variable but the programming would force when I ran it.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include <string.h>
struct node {
char * data;
struct node * next;
};
struct hashtable {
struct node ** table;
int size;
int nentries;
};
struct hashtable * hashtable_new(int size) {
struct hashtable * result;
result = malloc(sizeof(struct hashtable));
result -> size = size;
result -> nentries = 0;
result -> table = malloc(sizeof(struct node) * size);
int i = 0;
for (i = 0; i < result->size; i++) {
result->table[i] = NULL;
// result->table[i]->data = NULL;
}
return result;
}
unsigned hash_string(struct hashtable *this, char * str) {
unsigned hash = 0;
int i = 0;
for ( i = 0; str[i] != '\0'; i++ ) {
hash = hash * 37 + str[i];
}
//return hash;
return hash % this-> size;
}
void hashtable_free(struct hashtable * this) {
int i;
struct node *table_nodes, *current, *next;
for(i = 0; i<this->size; i++) {
table_nodes = this->table[i];
current = table_nodes;
while (current != NULL){
next = current->next;
free(current);
current = next;
}
this->table[i] = NULL;
}
free(&this->table);
free(&this->size);
free(&this->nentries);
free(this);
}
void hashtable_insert(struct hashtable * table, char * string) {
struct node * new_node;
unsigned index = hash_string(table, string);
if(table->table[index] == NULL) {
printf("\nIndex: %d", index);
new_node = malloc(sizeof(struct node));
new_node -> next = table->table[index];
new_node -> data = string;
printf("\nData: %s", new_node->data);
table -> table[index] = new_node;
table -> nentries++;
printf("\n");
} else {
new_node = malloc(sizeof(struct node));
new_node->data = string;
new_node->next = NULL;
struct node * current = table->table[index];
struct node * next;
int size = 1;
while (current != NULL) {
next = current->next;
//if(current->data == string){
//return;
//}
if(current-> next == NULL){
//last element in list
current->next = new_node;
table->nentries++;
size++;
printf("\nIndex: %d", index);
printf("\nSize: %d", size);
printf("\nData: %s", current->next->data);
printf("\n");
return;
}
current = next;
size++;
}
}
}
void remove_hash(struct hashtable * this, char * item) {
//unsigned index = hash_string(this, item);
}
int lookup(struct hashtable * this, char * item) {
struct node *temp;
unsigned int index = hash_string(this, item);
temp = this->table[index];
while(temp != NULL) {
// do something
printf("%s, ", temp->data);
if(temp->data == item) {
printf("found %s\n", temp->data);
}
temp = temp->next;
}
return 0;
}
void print(struct hashtable * this) {
int i = 0;
printf("\n Size %d \n", this->size);
if(this == NULL) {
printf("Please construct the hashtable");
return;
}
for (i = 0; i < this->size; i++) {
if(this->table[i] == NULL) {
printf("\n %d: <empty>", i);
} else {
printf("\n %d: %s ", i, this->table[i]->data);
if(this->table[i]->next != NULL) {
printf("%s ", this->table[i]->next->data);
}
}
}
}
int main(int argc, char **argv) {
//struct node *theNode;
struct hashtable *theHash;
theHash = hashtable_new(9);
hashtable_insert(theHash, "I");
hashtable_insert(theHash, "am");
hashtable_insert(theHash, "a");;
hashtable_insert(theHash, "fish");
hashtable_insert(theHash, "glub");
print(theHash);
hashtable_insert(theHash, "glub");
lookup(theHash, "I");
print(theHash);
//printf("\n\n\n");
hashtable_free(theHash);
//print(theHash);
return 0;
}
Since C doesn't let you pass by reference, you can try returning the hashtable then reassigning your variable with the result of hashtable_insert:
struct hashtable *hashtable_insert(struct hashtable *table, char *string) {
// awesome code here
return current;
}
And then call it with:
theHash = hashtable_insert(theHash, "Wow!");

Segmentation fault error in BST

I keep getting a segmentation fault error when I call the find_word function in my main.
when a word is added I want to return 1 and when it finds that word, I want it to return 1.
So I'm also not sure if my insert method is correct either.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct node {
char *word;
struct node *left;
struct node *right;
};
static struct node *root;
int init(void)
{
struct node *new_node = malloc (sizeof(struct node));
if(new_node==NULL){
return 0;
}
else{
root = new_node;
new_node->left = NULL;
new_node->right = NULL;
return 1;
}
}
static int insert(struct node *newnode, char *word)
{
struct node *temp = NULL;
if(!(newnode))
{
temp = (struct node *)malloc(sizeof(struct node));
temp->left =NULL;
temp->right = NULL;
temp->word = word;
newnode = temp;
return 0;
}
if(word < (newnode)->word)
{
insert((newnode)->left, word);
}
else if(word > (newnode)->word)
{
insert((newnode)->right, word);
}
return 1;
}
int add_word(char *word)
{
return insert(root,word);
}
static int find(char *word, struct node *newnode){
if(newnode==NULL){
return 0;
}
else if(strcmp(word,newnode->word)>0){
find(word,newnode->left);
}
else if(strcmp(newnode->word,word)<0){
find(word,newnode->right);
}
else{
return 1;
}
return 0;
}
int find_word(char *word)
{
return find(word,root);
}
int main(int argc,char *argv[])
{
int k;
char l[5];
k = init();
printf("init: %d\n",k);
strcpy(l,"x");
k = add_word(l);
printf("add_word(%s): %d\n",l,k);
strcpy(l,"x");
k = find_word(l);
printf("find_word(%s): %d\n",l,k);
return 0;
}
to fix like this
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct node {
char *word;
struct node *left;
struct node *right;
};
static struct node *root = NULL;
static int insert(struct node **newnode, char *word){
struct node *temp = NULL;
int cmp;
if(!*newnode){
temp = (struct node *)malloc(sizeof(struct node));
temp->left =NULL;
temp->right = NULL;
temp->word = strdup(word);
*newnode = temp;
return 0;
}
if((cmp=strcmp(word, (*newnode)->word)) < 0)
return insert(&(*newnode)->left, word);
if(cmp > 0)
return insert(&(*newnode)->right, word);
return 1;
}
int add_word(char *word){
return insert(&root, word);
}
static int find(char *word, struct node *newnode){
int cmp;
if(newnode==NULL)
return 0;
if((cmp=strcmp(word, newnode->word)) == 0)
return 1;
if(cmp < 0)
return find(word, newnode->left);
return find(word, newnode->right);
}
int find_word(char *word){
return find(word, root);
}
int main(int argc,char *argv[]){
int k;
char *w;
k = add_word(w="x");
printf("add_word(%s): %d\n", w, k);
k = find_word(w);
printf("find_word(%s): %d\n", w, k);
return 0;
}
If newnode->word is NULL, you should insert the word at the current node, to handle the empty root node.
static int insert(struct node *newnode, char *word)
{
struct node *temp = NULL;
if(!(newnode))
{
temp = (struct node *)malloc(sizeof(struct node));
temp->left =NULL;
temp->right = NULL;
temp->word = malloc(strlen(word)+1);
strcpy(temp->word, word);
newnode = temp;
return 0;
}
if (newnode->word == NULL) {
newnode->word = malloc(strlen(word)+1);
strcpy(newnode->word, word);
return 1;
}
if(strcmp(word,(newnode)->word) < 0)
{
insert((newnode)->left, word);
}
else if(strcmp(word,(newnode)->word) > 0)
{
insert((newnode)->right, word);
}
return 1;
}
In your find function, you call strcmp twice. You swap the order of the arguments, but you also change > 0 to < 0. These cancel each other out, so both are testing the same thing. You need to change one or the other, but not both. You should also check for newnode->word == NULL.
static int find(char *word, struct node *newnode){
if(newnode==NULL || newnode->word == NULL){
return 0;
}
else if(strcmp(word,newnode->word)>0){
find(word,newnode->left);
}
else if(strcmp(word,newnode->word)<0){
find(word,newnode->right);
}
else{
return 1;
}
return 0;
}

Resources