Segmentation fault while inserting into a hash table - c

I want to be able to use my getNextWord function to return a pointer to the next word in the file. I think I'm getting the seg fault while inserting but I just can't figure it out. Any help on this would be excellent. Also, I should probably find a better way of getting my hash_table_size than increasing a count for the total number of words in the file then rewinding. How can I make the size grow automatically?
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int hash_table_size;
char* getNextWord(FILE* fd) {
char c;
char buffer[256];
int putChar = 0;
while((c = fgetc(fd)) != EOF) {
if(isalnum(c)) break;
}
if(c == EOF) return NULL;
buffer[putChar++] = c;
while((c = fgetc(fd)) != EOF) {
if(isspace(c) || putChar >= 256 -1) break;
if(isalnum(c))
buffer[putChar++] = c;
}
buffer[putChar] = '\0';
return strdup(buffer);
}
struct node {
struct node *next;
int count;
char* key;
};
struct list {
struct node *head;
int count;
};
struct list *hashTable = NULL;
/*
* djb2 hash function
*/
unsigned int hash(unsigned char *str) {
unsigned int hash = 5381;
int c;
while(c == *str++)
hash = ((hash << 5) + hash) + c;
return (hash % hash_table_size);
}
struct node* createNode(char *key) {
struct node *new_node;
new_node = (struct node *)malloc(sizeof(struct node));
strcpy(new_node->key, key);
new_node->next = NULL;
return new_node;
}
void hashInsert(char *str) {
int hash_dex = hash(str);
struct node *new_node = createNode(str);
if(!hashTable[hash_dex].head) {
hashTable[hash_dex].head = new_node;
hashTable[hash_dex].count = 1;
return;
}
new_node->next = (hashTable[hash_dex].head);
hashTable[hash_dex].head = new_node;
hashTable[hash_dex].count++;
return;
}
void display() {
struct node *current;
int i;
while(i < hash_table_size) {
if(hashTable[i].count == 0)
continue;
current = hashTable[i].head;
if(!current)
continue;
while(current != NULL) {
char tmp[256];
strcpy(tmp, current->key);
printf("%s", tmp);
current = current->next;
}
}
return;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: ./hashFile textfile\n");
}
else {
FILE *file = fopen(argv[1], "r");
if(file == 0) {
printf("Could not open file\n");
}
else {
char *new_word;
while((new_word = getNextWord(file)) != NULL) {
hash_table_size++;
}
rewind(file);
hashTable = (struct list *)calloc(hash_table_size, sizeof(struct list));
while((new_word = getNextWord(file)) != NULL) {
hashInsert(new_word);
}
display();
fclose(file);
}
}
return 0;
}

int c;
while(c == *str++)
hash = ((hash << 5) + hash) + c;
c is not initialized here. As is i in display function. Please enable all the compiler warnings and fix them.
Also:
char c;
char buffer[256];
int putChar = 0;
while((c = fgetc(fd)) != EOF) {
if(isalnum(c)) break;
}
c has to be of type int not char.

change
while(c == *str++)
to
while(c = *str++)

Related

Double pointer in the function

I am trying to insert strings in the binary search tree.
So what I am to trying is,
parsing strings from a file(contains instruction set) and then inserting in the function
insertOpcodeFromFile().
So this function will execute
(*node) = Node_insert(&node,instruction).
the node will be the root of binary tree which is located in main function.
So in simple way to explain, I want to manipulate(insert) the root pointer in the main function by using double pointer in the other function contain insert function.
I have a simple understanding about the pointer, but in this situation, I need to use more than double pointer I think.
please explain me about the double pointer clearly using this example.
Here is my code(I commenting out insert_node)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef BINARYTREE_H_
#define BINARYTREE_H_
typedef struct node *NodePtr;
typedef struct node {
char *word;
int count;
NodePtr left;
NodePtr right;
} Node;
NodePtr Node_alloc();
NodePtr Node_insert(NodePtr node_ptr, char *word);
void clearArray(char a[]);
void insertOpcodeFromFile(FILE *opcodeFile, NodePtr *node);
void Node_display(NodePtr);
char *char_copy(char *word);
#endif
int main(int argc, const char * argv[]) {
FILE * opFile;
FILE * progFile;
struct node *root = NULL;
if ( argc != 4) { // # of flag check
fprintf(stderr, " # of arguments must be 4.\n" );
exit(1);
}
opFile = fopen ( argv[1], "r");
if(opFile == NULL)
{
fprintf(stderr,"There is no name of the opcode file\n");
exit(1);
}
progFile = fopen ( argv[2], "r");
if(progFile == NULL)
{
fprintf(stderr,"There is no name of the program file \n");
exit(1);
}
insertOpcodeFromFile(opFile, &root);
//Node_display(root);
}/* main is over */
void insertOpcodeFromFile(FILE *opcodeFile, NodePtr *node)
{
int fsize = 0;
int lengthOfInst = 0;
int c;
int i;
char buffer[100];
fsize = getFileSize(opcodeFile);
enum flag {ins,opc,form};
int flag = ins;
char instruction[6];
unsigned int opcode = 0;
unsigned char format;
while (c != EOF)
{
c = fgetc(opcodeFile);
buffer[i++] = c;
if (c == 32){
switch (flag) {
case ins:
flag = opc;
memcpy(instruction,buffer,i);
instruction[i] = '\0';
clearArray(buffer);
i = 0;
// printf("인스트럭션 : %s\n",instruction );
break;
case opc:
flag = form;
opcode = atoi(buffer);
clearArray(buffer);
i = 0;
// printf("옵코드 : %d\n",opcode );
break;
default:
break;
}/* end of switch */
}/* end of if(space) */
if((c == 10) || (c == EOF))
{
if (flag == form)
{
format = buffer[0];
clearArray(buffer);
i = 0;
// printf("포멧: %c\n", format);
}
flag = ins;
//node = Node_insert(node,instruction);
}
}
//Node_display(node);
}
int getFileSize(FILE *opcodeFile)
{ int fsize = 0;
fseek(opcodeFile,0, SEEK_SET);
fseek(opcodeFile,0, SEEK_END);
fsize = (int)ftell(opcodeFile);
fseek(opcodeFile,0, SEEK_SET);
return fsize;
}
int countUntilSpace(FILE *opcodeFile, int currentPosition)
{ char readword[1];
char *space = " ";
char *nextLine = "/n";
int i = 0;
//printf("현재: %d\n",currentPosition );
while(1)
{
fread(readword, sizeof(char),1,opcodeFile);
i++;
if(strcmp(readword,space) == 0 || strcmp(readword,nextLine) == 0)
{
//printf("break\n");
break;
}
}
fseek(opcodeFile,currentPosition ,SEEK_SET);
//printf("끝난 현재 :%d\n",ftell(opcodeFile) );
//printf("%I : %d\n",i );
return i - 1;
}
void clearArray(char a[])
{
memset(&a[0], 0, 100);
}
NodePtr Node_alloc()
{
return (NodePtr) malloc(sizeof(NodePtr));
}
NodePtr Node_insert(NodePtr node_ptr, char *word)
{
int cond;
if (node_ptr == NULL) {
node_ptr = Node_alloc();
node_ptr->word = char_copy(word);
node_ptr->count = 1;
node_ptr->left = node_ptr->right = NULL;
} else if ((cond = strcmp(word, node_ptr->word)) == 0) {
node_ptr->count++;
} else if (cond < 0) {
node_ptr->left = Node_insert(node_ptr->left, word);
} else {
node_ptr->right = Node_insert(node_ptr->right, word);
}
return node_ptr;
}
void Node_display(NodePtr node_ptr)
{
if (node_ptr != NULL) {
Node_display(node_ptr->left);
printf("%04d: %s\n", node_ptr->count, node_ptr->word);
Node_display(node_ptr->right);
}
}
char *char_copy(char *word)
{
char *char_ptr;
char_ptr = (char *) malloc(strlen(word) + 1);
if (char_ptr != NULL) {
char_ptr = strdup(word);
}
return char_ptr;
}
In this case, in main(),
Node *root;
Why do you need to use a "double" pointer ( Node ** ) in functions that alter root is because root value as to be set in these functions.
For instance, say you want to allocate a Node and set it into root.
If you do the following
void alloc_root(Node *root) {
root = malloc(sizeof (Node));
// root is a function parameter and has nothing to do
// with the 'main' root
}
...
// then in main
alloc_root( root );
// here main's root is not set
Using a pointer to pointer (that you call "double pointer")
void alloc_root(Node **root) {
*root = malloc(sizeof (Node)); // note the *
}
...
// then in main
allow_root( &root );
// here main's root is set
The confusion comes probably from the Node *root in main, root being a pointer to a Node. How would you set an integer int i; in a function f? You would use f(&i) to call the function f(int *p) { *p = 31415; } to set i to the value 31415.
Consider root to be a variable that contains an address to a Node, and to set its value in a function you have to pass &root. root being a Node *, that makes another *, like func(Node **p).

Prefix tree implementation for C

I am trying to write a C program that provides autocomplete suggestions looking at the contents of a directory. I have most of it done, however I get errors where directory names contain symbols that are not alphabets (such as . , / _). I get errors whenever I try to change things, including array size and looping values. Could you please take a look at my code and suggest what changes I need to make to include symbols in autocomplete suggestions.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#define MAX 1000
struct node {
int data;
struct node *array[26];
};
struct node* new_node(struct node *h)
{
int i;
h = malloc(sizeof (struct node));
for (i = 0; i < 24; ++i)
h->array[i] = 0;
return h;
}
struct node* insert(struct node *h, char *c, int value)
{
int i;
if (strlen(c) == 0)
return h;
if (h == NULL)
h = new_node(h);
struct node *p = h;
for (i = 0; i < strlen(c); ++i) {
if (p->array[c[i] - 'a'] == NULL)
p->array[c[i] - 'a'] = malloc(sizeof (struct node));
p = p->array[c[i] - 'a'];
}
p->data = value;
return h;
}
int dfs(struct node *h, char *dat)
{
int i;
char k[1000] = {0};
char a[2] = {0};
if (h == NULL)
return 0;
if (h->data > 0)
printf("Match: %s\n", dat);
for(i = 0; i < 26; ++i) {
strcpy(k, dat);
a[0] = i + 'a';
a[1] = '\0';
strcat(k, a);
dfs(h->array[i], k);
}
}
void search(struct node *h, char *s, char *dat)
{
int i;
char l[1000] = {0};
char a[2];
strcpy(l, dat);
if (strlen(s) > 0) {
a[0] = s[0];
a[1] = '\0';
if(h->array[a[0]-'a'] != NULL) {
strcat(dat, a);
search(h->array[a[0]-'a'], s+1, dat);
} else
printf("No Match \n");
} else {
if (h->data != 0)
printf("Match: ");
for (i = 0; i < 26; ++i) {
strcpy(l, dat);
a[0] = i + 'a';
a[1] = '\0';
strcat(l, a);
dfs(h->array[i], l);
}
}
}
struct node* read_keys(struct node *h, char *file)
{
char s[MAX];
FILE *a = fopen(file, "r");
if (a == NULL)
printf("Error while opening file");
else
while (feof(a) == 0) {
fscanf(a, "%s", s);
h = insert(h, s, 1);
}
return h;
}
int main()
{
DIR *d;
struct dirent *dir;
char direct[MAX];
printf("Enter a folder name: ");
scanf("%s",direct);
d = opendir(direct);
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
if (d)
{
while ((dir = readdir(d)) != NULL)
{
fprintf(f,"%s\n", dir->d_name);
}
}
fclose(f);
char c[1000];
FILE *fptr;
if ((fptr = fopen("file.txt", "r")) == NULL)
{
printf("Error! opening file");
exit(1);
}
FILE* file = fopen("file.txt", "r");
char line[1000];
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(fptr);
printf("Enter beginning of filename \n");
struct node *h = 0;
h = read_keys(h, "file.txt");
char s[MAX];
scanf("%s", s);
char dat[1000] = "";
search(h, s, dat);
return 0;
}

Cannot delete vowels from singly linked list

I am having an issue while deleting the vowel from a linked List. The program accept command line arguments, combines them in a single string and add each character to a linked list as node.
When i try to run the program with command line argument "lemon", the successfully deletes the vowels. i.e the program deletes the vowels successfully if the argument doesn't contain consequetive vowels.
On the other hand, if i try to do the same with command line argument "aeiou", the program crashes with message Segmentation fault(core dumped).. I am not getting any idea how to handle this..
The program must not create any global variables so i've used double pointer.
All the functions are working properly this problem may have occured due to some mistakes in locate() and removeVowels() function but i cannot figure out what the mistake is.
can this problem be solved using double pointer??
I cannot figure out what is wrong in this program.. I am new to c programming, please help me with this.. Please rectify me..
Thanks in advance.
The complete code is given below:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct linkedList {
char ch;
struct linkedList *node;
};
void printMenu(void);
char* combineWithNoSpaces(int, char *[]);
void addTolinkedList(char *, struct linkedList **, int *);
void printLinkedList(struct linkedList **);
struct linkedList *locate(struct linkedList**);
int delHead(struct linkedList **);
void removeVowels(struct linkedList**);
int isEmpty(struct linkedList **);
int main(int argc, char *argv[]) {
int choice, indexer = 0;
struct linkedList *s;
char *string;
if (argc == 1) {
printf("Parse a sentence");
} else {
s = (struct linkedList *) malloc(sizeof(struct linkedList));
string = combineWithNoSpaces(argc, argv);
addTolinkedList(string, &s, &indexer);
while (1) {
printMenu();
scanf("%d", &choice);
if (choice == 1) {
printLinkedList(&s);
} else if (choice == 2) {
if (!delHead(&s))
printf("Failed.Empty linked list");
} else if (choice == 3) {
removeVowels(&s);
} else if (choice == 4) {
if(isEmpty(&s)){
printf("Empty LinkedList");
}
else
printf("Not Empty");
} else if (choice == 5) {
break;
} else
printf("Invalic choice");
printf("\n");
}
}
return 0;
}
int isEmpty(struct linkedList **s){
if(*s == NULL)
return 1;
else
return 0;
}
struct linkedList *locate(struct linkedList **s) {
if ((*s)->node->ch == 'a' || (*s)->node->ch == 'e' || (*s)->node->ch == 'i'
|| (*s)->node->ch == 'o' || (*s)->node->ch == 'u'
|| (*s)->node->ch == 'A' || (*s)->node->ch == 'E'
|| (*s)->node->ch == 'I' || (*s)->node->ch == 'O'
|| (*s)->node->ch == 'U') {
return *s;
} else if ((*s)->node->node == NULL) {
return NULL;
} else
return locate(&((*s)->node));
}
void removeVowels(struct linkedList **s) {
struct linkedList *temp, *tag;
/* Checking whether the first node is null or not */
if ((*s)->ch == 'a' || (*s)->ch == 'e' || (*s)->ch == 'i'
|| (*s)->ch == 'o' || (*s)->ch == 'u'
|| (*s)->ch == 'A' || (*s)->ch == 'E'
|| (*s)->ch == 'I' || (*s)->ch == 'O'
|| (*s)->ch == 'U')
delHead(s);
do {
tag = locate(s);
if (tag != NULL) {
temp = tag->node->node;
free(tag->node);
tag->node = temp;
}
} while (tag != NULL);
}
int delHead(struct linkedList **s) {
struct linkedList *temp;
if ((*s) == NULL) {
return 0;
} else {
temp = (*s)->node;
free(*s);
*s = temp;
return 1;
}
}
void printLinkedList(struct linkedList **s) {
if ((*s) != NULL) {
printf("%c", (*s)->ch);
printLinkedList(&(*s)->node);
}
return;
}
void addTolinkedList(char *str, struct linkedList **s, int *indexer) {
if (*indexer == strlen(str)) {
*s = NULL;
return;
} else {
(*s)->ch = *(str + *indexer);
(*s)->node = (struct linkedList *) malloc(sizeof(struct linkedList));
++*indexer;
addTolinkedList(str, &(*s)->node, indexer);
}
}
char * combineWithNoSpaces(int argc, char *argv[]) {
int i, j;
int count = 0;
int memory = 0;
char *str;
for (i = 1; i < argc; i++) {
for (j = 0; j < strlen(argv[i]); j++) {
++memory;
}
}
str = (char *) malloc(memory * sizeof(char) + 1);
for (i = 1; i < argc; i++) {
for (j = 0; j < strlen(argv[i]); j++) {
*(str + count) = argv[i][j];
++count;
}
}
return str;
}
void printMenu(void) {
printf("\n\n"
"1. print input arguments (no spaces)\n"
"2. remove first character\n"
"3. remove vowels\n"
"4. is the linked list empty?\n"
"5. exit program\n"
"Enter your choice>");
}
The screen shot for output is :
For argument lemon
For argument aeiou
This code works to my satisfaction. It is more nearly an MCVE (Minimal, Complete, Verifiable Example.
I called the program rv19. When run like this, it gives the output shown:
$ rv19 apple
[apple]
[ppl]
$ rv19 nutmeg
[nutmeg]
[ntmg]
$ rv19 ply
[ply]
[ply]
$ rv19 aeiou
[aeiou]
[]
$ rv19 aardvark abstemiously facetiously aeiou minions lampoon shampoo
[aardvarkabstemiouslyfacetiouslyaeiouminionslampoonshampoo]
[rdvrkbstmslyfctslymnnslmpnshmp]
$
The code (rv19.c):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct linkedList
{
char ch;
struct linkedList *node;
};
char *combineWithNoSpaces(int, char *[]);
void addTolinkedList(char *, struct linkedList **, int *);
void printLinkedList(struct linkedList **);
struct linkedList *locate(struct linkedList **);
int delHead(struct linkedList **);
void removeVowels(struct linkedList **);
void freeLinkedList(struct linkedList *);
int main(int argc, char *argv[])
{
int indexer = 0;
struct linkedList *s;
char *string;
if (argc == 1)
{
printf("Parse a sentence. Usage: %s word [word ...]\n", argv[0]);
}
else
{
s = (struct linkedList *) malloc(sizeof(struct linkedList));
printf("s = %p\n", (void *)s);
string = combineWithNoSpaces(argc, argv);
addTolinkedList(string, &s, &indexer);
printLinkedList(&s);
removeVowels(&s);
printLinkedList(&s);
printf("s = %p\n", (void *)s);
freeLinkedList(s);
free(string);
}
return 0;
}
static inline int isvowel(char c)
{
return(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
}
struct linkedList *locate(struct linkedList **s)
{
if ((*s)->node == NULL)
return NULL;
if (isvowel((*s)->node->ch))
{
return *s;
}
else if ((*s)->node == NULL)
{
return NULL;
}
else
return locate(&((*s)->node));
}
void removeVowels(struct linkedList **s)
{
struct linkedList *temp, *tag;
/* Remove leading vowels */
while ((*s) != NULL && isvowel((*s)->ch))
{
//printf("Remove leading '%c'\n", (*s)->ch);
struct linkedList *ts = *s;
delHead(&ts);
*s = ts;
}
struct linkedList *n = *s;
while (n != NULL && (tag = locate(&n)) != NULL)
{
/* Remove multiple embedded or trailing vowels */
while (tag->node != NULL && isvowel(tag->node->ch))
{
temp = tag->node;
tag->node = tag->node->node;
free(temp);
}
n = tag->node;
}
}
int delHead(struct linkedList **s)
{
struct linkedList *temp;
if ((*s) == NULL)
return 0;
else
{
temp = (*s)->node;
free(*s);
*s = temp;
return 1;
}
}
void printLinkedList(struct linkedList **s)
{
struct linkedList *n = *s;
putchar('[');
while (n != NULL)
{
putchar(n->ch);
n = n->node;
}
putchar(']');
putchar('\n');
}
void addTolinkedList(char *str, struct linkedList **s, int *indexer)
{
if (*indexer == (int)strlen(str))
{
free(*s);
*s = NULL;
}
else
{
(*s)->ch = *(str + *indexer);
(*s)->node = (struct linkedList *) malloc(sizeof(struct linkedList));
++*indexer;
addTolinkedList(str, &(*s)->node, indexer);
}
}
char *combineWithNoSpaces(int argc, char *argv[])
{
int argl[argc+1];
int memory = 0;
for (int i = 1; i < argc; i++)
{
argl[i] = strlen(argv[i]);
memory += argl[i];
}
char *str = (char *) malloc(memory + 1);
char *base = str;
for (int i = 1; i < argc; i++)
{
strcpy(base, argv[i]);
base += argl[i];
}
return str;
}
void freeLinkedList(struct linkedList *node)
{
while (node != NULL)
{
struct linkedList *next = node->node;
free(node);
node = next;
}
}
This is still not as polished as it could be. I changed the printing so as to get a marker before the start and after the end of the output; it is easier to see unwanted blanks and other characters like that. It's now iterative. I'd change the interface to the function, too, so it takes a struct linkedList * instead of a struct linkedList **. The code in removeVowels() is tricky; it iterates to remove repeated initial vowels; it iterates to remove repeated vowels after a non-vowel. The locate() function now returns a pointer to a non-vowel node that has a vowel in the next node. This code frees both the string and the list (using a new function, freeLinkedList() to free the list).
I've checked it with a couple of debugging versions of malloc(), and it seems to be leak free and corruption free.
I still haven't run it with valgrind because I can't get it to run properly after building it on macOS Sierra 10.12:
valgrind: mmap-FIXED(0x0, 253952) failed in UME (load_segment1) with error 12 (Cannot allocate memory).
This was with the latest code downloaded from SVN (revision 16097).
I tried to simplify all the functions -- some were taking (pointers to) pointers as arguments when they needn't do so.
A few highlights of the many changes:
main: changed the main control structure to a switch statement. Initialized the linkedList pointer to NULL instead of a malloc'd one as entering an empty string would cause addTolinkedList() to leak this memory. Added a call to new function freeLinkedList() when the exit option is selected.
locate: renamed this locateVowel() and restructured with removeVowel() to have only one place that actually looks for vowels. Removed potential memory leak.
combineWithNoSpaces: rewrote this to be string oriented instead of character oriented.
addTolinkedList: made the index(er) argument a simple int that gets incremented on recursion which simplified a number of issues.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct linkedList {
char ch;
struct linkedList *node;
};
void printMenu(void);
char* combineWithNoSpaces(int, char *[]);
void addTolinkedList(char *, struct linkedList **, int);
void printLinkedList(struct linkedList *);
struct linkedList **locateVowel(struct linkedList **);
bool delHead(struct linkedList **);
void removeVowels(struct linkedList **);
bool isEmpty(struct linkedList *);
void freeLinkedList(struct linkedList *);
int main(int argc, char *argv[]) {
int choice;
char *string;
if (argc == 1) {
fprintf(stderr, "Enter a sentence\n");
return EXIT_FAILURE;
}
struct linkedList *s = NULL;
string = combineWithNoSpaces(argc, argv);
addTolinkedList(string, &s, 0);
free(string);
while (true) {
printMenu();
(void) scanf("%d", &choice);
printf("\n");
switch (choice) {
case 1:
printLinkedList(s);
break;
case 2:
if (!delHead(&s)) {
printf("Failed. Empty linked list\n");
}
break;
case 3:
removeVowels(&s);
break;
case 4:
if (isEmpty(s)) {
printf("Empty LinkedList\n");
} else {
printf("Not Empty\n");
}
break;
case 5:
freeLinkedList(s);
return EXIT_SUCCESS;
default:
printf("Invalid choice\n");
}
}
return EXIT_SUCCESS;
}
bool isEmpty(struct linkedList *s) {
return (s == NULL);
}
struct linkedList **locateVowel(struct linkedList **s) {
if (*s == NULL) {
return NULL;
}
char ch = tolower((*s)->ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
return s;
}
return locateVowel(&((*s)->node));
}
void removeVowels(struct linkedList **s) {
struct linkedList **vowel;
while ((vowel = locateVowel(s)) != NULL) {
struct linkedList *temporary = (*vowel)->node;
if (temporary == NULL) {
free(*vowel); // a vowel with nothing following it
*vowel = NULL;
break;
}
(*vowel)->ch = temporary->ch;
(*vowel)->node = temporary->node;
free(temporary);
s = vowel;
}
}
bool delHead(struct linkedList **s) {
if (*s == NULL) {
return false;
}
struct linkedList *temporary = (*s)->node;
free(*s);
*s = temporary;
return true;
}
void printLinkedList(struct linkedList *s) {
printf("\"");
while (s != NULL) {
printf("%c", s->ch);
s = s->node;
}
printf("\"\n");
}
void addTolinkedList(char *string, struct linkedList **s, int index) {
if (index == strlen(string)) {
*s = NULL;
} else {
*s = malloc(sizeof(struct linkedList));
(*s)->ch = string[index];
(*s)->node = NULL;
addTolinkedList(string, &(*s)->node, index + 1);
}
}
char *combineWithNoSpaces(int argc, char *argv[]) {
int characters = 0;
for (int i = 1; i < argc; i++) {
characters += strlen(argv[i]);
}
char *string = calloc(characters + 1, 1);
for (int i = 1; i < argc; i++) {
(void) strcat(string, argv[i]);
}
return string;
}
void freeLinkedList(struct linkedList *s) {
while (s != NULL) {
struct linkedList *temporary = s;
s = s->node;
free(temporary);
}
}
void printMenu(void) {
printf("\n"
"1. print string (no spaces)\n"
"2. remove first character\n"
"3. remove vowels\n"
"4. is the linked list empty?\n"
"5. exit program\n"
"Enter your choice: ");
}

read txt, count each alphabet using linked list

#pragma warning (disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <ctype.h>
#define NUM_OF_ALPHABET 26
#define MAX_HEAP_SIZE 100
typedef struct _CharFrequency
{
char character;
int frequency;
struct _CharFrequency * next;
}CharFrequency;
typedef CharFrequency* pCharFrequency;
pCharFrequency pHead = NULL;
void initList();
void addNode(char ch);
void printAllNode(pCharFrequency pHead);
int main()
{
int i = 0, cnt = 0;
FILE *pFile;
char readLine[1024], *ptr;
char *token = " \t\n.";
pFile = fopen("C:\\Users\\Home\\Desktop\\dataset.txt", "r");
if (pFile == NULL)
{
printf("File open failed.\n");
return 0;
}
while (fgets(readLine, 1024, pFile) != NULL)
{
ptr = strtok(readLine, token);
while (ptr != NULL)
{
for (i = 0; i < strlen(ptr); i++)
{
addNode(ptr[i]);
}
ptr = strtok(NULL, token);
}
}
printAllNode(pHead);
return 0;
}
void initList()
{
pHead = (CharFrequency*)malloc(sizeof(CharFrequency));
if (!pHead)
{
printf("Fault\n");
return;
}
pHead->character = '\0';
pHead->frequency = 0;
pHead->next = NULL;
}
void addNode(char ch)
{
int i = 0;
pCharFrequency pNode = NULL;
pCharFrequency pCurrent= NULL;
if (isalpha(ch) == 0)
return;
if (ch >= 'A' && ch <= 'Z')
ch = ch + 32;
printf("%c ", ch);
for (pCurrent = pHead; pCurrent != NULL ; pCurrent = pCurrent->next)
{
if (pCurrent->character == ch)
{
pCurrent->frequency++;
}
else
{
pNode = (CharFrequency*)malloc(sizeof(CharFrequency));
pNode->frequency = 0;
pNode->next = NULL;
pNode->character = ch;
pNode->frequency++;
pCurrent->next = pNode;
}
}
pNode = (CharFrequency*)malloc(sizeof(CharFrequency));
pNode->frequency = 0;
pNode->next = NULL;
pNode->character = ch;
pNode->frequency++;
pCurrent->next = pNode;
}
void printAllNode(pCharFrequency pHead)
{
pCharFrequency pCurrent;
pCurrent = pHead;
pCurrent = pHead;
while (pCurrent->next != NULL) {
printf("%c %d", pCurrent->character, pCurrent->frequency);
pCurrent = pCurrent->next;
}
}
I want to build a program that reads txt file, count only alphabet, and count them using linked list. I make struct called CharFrequency to count alphabet.
addNode function gets the character, checks if it's in the list or not, and count them.
It makes error when doing for() in the addNode function.
You need to rethink about the logic inside your addNode method. It is adding a new node every time a character is not found in the list, and even if a match is found,the loop will continue until the last node adding a new node every time.
You could do something like this to get you started and experiment on it to make it more efficient.
pCharFrequency pNode = NULL;
pCharFrequency pCurrent= NULL;
pCharFrequency pTail= NULL;//this will keep track of the last node in the list
//so that we use it to insert a new node
....//your other code
pCurrent = pHead;//start from the head
while (pCurrent!=NULL)
{
if (pCurrent->character == ch)
{
pCurrent->frequency++;
return;//if a match was found, count and return
}
if(pCurrent->next == NULL)
pTail=pCurrent;//save the pointer to the last node in the list if we reach to it
pCurrent=pCurrent->next;//get the next node
}
//if we reach here, then we need to create a new node
pNode = (CharFrequency*)malloc(sizeof(CharFrequency));
if(pNode==NULL)
{
//show error message
return;
}
pNode->frequency = 1;
pNode->next = NULL;
pNode->character = ch;
if(pHead==NULL)
pHead=pNode;//for the very first node,we just assign to head
else
pTail->next = pNode;//otherwise set the last node's next to the node we just created

Error Compiling an Deterministic Pushdown Automaton in C (DPDA)

I was reading about how to implement a DPDA and found this code in the following Internet address: http://code.zhoubot.com/, This c file implements a simple pushdown automata. The automata will read in a description of their transition function and input, perform its computation on the input, and then print their output.
The input format is like:
e01:e0$:000111:a:ad:aeeb$:b0eb0:b10ce:c10ce:ce$de
The input is separated by a semicolon “:”, first section is “input alphabet”, second is “stack alphabet”, then “input” and the last whole bunch are transition functions.
/* This C file implements a Deterministic Pushdown Automata
* author: Kevin Zhou
* Computer Science and Electronics
* University of Bristol
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct stack {
char content;
struct stack *next;
} Stack;
typedef struct transistion {
char current_state;
char input_symbol;
char pull;
char new_state;
char push;
} Transistion;
/* list of transistion functions */
typedef struct list {
Transistion *content;
struct list *next;
} List;
typedef struct pda {
char *input_alpha;
char *stack_alpha;
char *input;
char start;
char *accept;
List *transistion;
} PDA;
/* create a new empty stack */
Stack *create_stack( void ) {
Stack *s = calloc(1,sizeof(Stack));
if(s==NULL) {
printf("Out of Memory!");
exit(1);
}
return s;
}
/* test if the stack is empty */
int isempty( Stack *s ) {
return (s->next==NULL)? 1:0;
}
Stack *push_stack (Stack *s, char c) {
Stack *new = calloc(1,sizeof(Stack));
if(new ==NULL) {
printf("Out of Memory!");
exit(1);
}
new -> content = c;
new -> next = s;
return new;
}
Stack *pull_stack (Stack *s) {
Stack *head;
if(isempty(s)) {
return '\0';
}
head = s;
s = head -> next;
return s;
}
/*return the top elememt in the stack */
char top (Stack *s) {
return s->content;
}
/* replace a value 'ontop' which on top of the stack with a newvalue 'newvalue'
epsilon represents an empty element*/
Stack *replace(Stack *sta, char ontop, char newvalue, char epsilon) {
if(ontop == epsilon && newvalue == epsilon) return sta;
if(ontop == epsilon && newvalue != epsilon) {
sta = push_stack(sta,newvalue);
return sta;
}
if(ontop != epsilon && newvalue == epsilon) {
if(ontop != top(sta)) return NULL;
sta = pull_stack(sta);
return sta;
}
if(ontop != top(sta)) return NULL;
sta = pull_stack(sta);
sta = push_stack(sta,newvalue);
return sta;
}
/* turn the input string into transistion fields */
Transistion *get_transistion(char *s) {
Transistion *t = calloc(1,sizeof(Transistion));
t->current_state = s[0];
t->input_symbol = s[1];
t->pull = s[2];
t->new_state = s[3];
t->push = s[4];
return t;
}
/* turn the string into transitions and add into list */
List *insert_list( List *l, char *elem ) {
List *t = calloc(1,sizeof(List));
List *head = l;
while(l->next!=NULL)
l = l->next;
t->content = get_transistion(elem);
t->next = NULL;
l->next = t;
return head;
}
/* insert a transistion into a list */
List *insert_list_transistion( List *l, Transistion *tr) {
List *t = calloc(1,sizeof(List));
List *head = l;
while(l->next!=NULL)
l = l->next;
t->content = tr;
t->next = NULL;
l->next = t;
return head;
}
/*test if the char c is in the string s */
int contains ( char c, char *s ) {
int i=0;
while(1) {
if(c== s[i]) return 1;
if(s[i] == '\0') return 0;
i++;
}
}
/* test if the input is a valid input */
int is_valid_input( char *input_alpha, char *input ) {
int i=0;
char c;
while(1) {
c = input[i];
if(c == '\0') break;
if(!contains(c,input_alpha)) return 0;
i++;
}
return 1;
}
/* test if the input is a valid transistion */
int is_valid_transistion ( List *l, PDA *m) {
Transistion *t;
while(1) {
if(l==NULL) break;
t = l->content;
if(!contains(t->input_symbol,m->input_alpha)) return 0;
if(!contains(t->pull,m->stack_alpha)) return 0;
if(!contains(t->push,m->stack_alpha)) return 0;
l = l->next;
}
return 1;
}
/* create a pushdown automata */
PDA *createPDA (char *input) {
PDA *m = calloc(1,sizeof(PDA));
List *tr = calloc(1,sizeof(List));
char *buffer;
char *epsilon = calloc(1,sizeof(char));
/*read input alphabet of PDA*/
buffer = strtok(input,":");
if(buffer == NULL) {
printf("Error in reading input alphabet!\n");
exit(1);
}
m->input_alpha = buffer;
epsilon[0] = m->input_alpha[0];
/*read stack alphabet*/
buffer = strtok(NULL,":");
if(buffer == NULL) {
printf("Error in reading stack alphabet!\n");
exit(1);
}
m->stack_alpha = buffer;
/*read input sequence*/
buffer = strtok(NULL,":");
if(buffer == NULL) {
printf("Error in reading input sequence!\n");
exit(1);
}
if(!is_valid_input(m->input_alpha,buffer)) {
printf("Error! Input contains some invalid characters that don't match the input alphabet!\n");
exit(1);
}
m->input = buffer;
/*read start state*/
buffer = strtok(NULL,":");
if(buffer == NULL) {
printf("Invalid string!\n");
exit(1);
}
m->start = buffer[0];
/*read accept state*/
buffer = strtok(NULL,":");
if(buffer == NULL) {
printf("Invalid string!\n");
exit(1);
}
m->accept = buffer;
/*read transistion function*/
while(1) {
buffer = strtok(NULL,":");
if(buffer == NULL) break;
tr = insert_list(tr,buffer);
}
if(!is_valid_transistion(tr->next,m)) {
printf("Error! Invalid transistion functions!\n");
exit(1);
}
m->transistion = tr->next;
return m;
}
/*print a stack */
void print_stack2(Stack *s) {
if(s==NULL) {
return;
}
print_stack2(s->next);
printf("%c",s->content);
}
void print_stack(Stack *s) {
print_stack2(s);
printf("\n");
}
/* find a proper transition function for the current state */
Transistion *find_transistion(List *list,char input,char current,char e) {
Transistion *t;
while(1) {
if(list==NULL) return NULL;
t = list -> content;
if(t->current_state == current && t->input_symbol == input)
return t;
if(t->current_state == current && t->input_symbol == e)
return t;
list = list->next;
}
}
int isAccept(char current, char* accept) {
int i=0;
while(1) {
if(accept[i]=='\0') return 0;
if(accept[i]==current) return 1;
i++;
}
}
/*simulate the Pushdown automata */
void simulate(PDA *m) {
/* first symbol in input symbol used to represent the usual */
const char epsilon = m->input_alpha[0];
char current_state = m->start;
char input;
int i=0;
Stack *sta = create_stack();
Transistion *current_transistion;
Stack *backup;
while(1) {
/*get input*/
input = m->input[i];
if(input == '\0'&&isAccept(current_state,m->accept)) {
printf("Accept\n");
print_stack(sta);
break;
}
/*get transistion function*/
current_transistion = find_transistion(m->transistion,input,current_state,epsilon);
if(current_transistion==NULL) {
printf("Reject\n");
print_stack(sta);
break;
}
current_state = current_transistion->new_state;
backup = sta;
sta = replace(sta, current_transistion->pull, current_transistion->push,epsilon);
if(sta == NULL) {
printf("Reject\n");
print_stack(backup);
break;
}
if(current_transistion->input_symbol != epsilon&&current_transistion->input_symbol != '\0')
i++;
}
}
void print(PDA *m) {
printf("input alphabet:%s\n",m->input_alpha);
printf("stack alphabet:%s\n",m->stack_alpha);
printf("input sequence:%s\n",m->input);
printf("start state:%c\n",m->start);
printf("accept state:%s\n",m->accept);
}
int main(void) {
char s[300];
PDA *p;
scanf("%s",s);
p = createPDA(s);
simulate(p);
return 0;
}
When trying to compile, the compiler tells me the following error:
Line 41: "error: invalid conversion from 'void *' to 'Stack *'
how I can fix this error, since I'm trying to understand
code?
You are likely using a C++ compiler instead of a C one. In C it's not required (it's actually discouraged) to cast void *. In C++ it's mandatory.
Incidentally, this C FAQ answers your problem. This one explains why casting void * can be problematic.

Resources