#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define ALPHABET_LENGTH 26
#define OPERATION_BUF_SIZE 5
#define NAME_BUF_SIZE 22
#define MAX_BUF_SIZE 27
#ifndef NULL
#define NULL ((void*)0)
#endif
/* Basic trie node -- also, keep track of number of nodes below this one. */
typedef struct node {
int num_children;
struct node *children[ALPHABET_LENGTH];
} trie_node;
trie_node* init(trie_node* a) {
a->num_children = 0;
for (int i = 0; i < ALPHABET_LENGTH; ++i)
{
a->children[i] = NULL;
}
return a;
}
char* trim(char* a){
if (a[0] == 'a')
{
a += 4;
}else{
a += 5;
}
return a;
}
void add(char* a, trie_node* node){//need to make sure a is not NULL at beginning
trie_node* newNode = malloc(sizeof(struct node));
newNode = init(newNode);
int i;
if ((a != NULL && a[0] !='\n') && node->children[a[0] - 97] == NULL)
{
node->num_children++;
//initialize the children array
for (i = 0; i < ALPHABET_LENGTH; i++)
{
if (newNode->children[i] != NULL)
{
newNode->children[i] = NULL;
}
}
newNode -> num_children = 0;
node->children[a[0] - 97] = newNode;
a++;
add(a, newNode);
}
else if ((a != NULL && a[0] !='\n') && node->children[a[0] - 97] != NULL){
a++;
node->num_children++;
add(a, node->children[a[0] - 97]);
} else{//a == NULL, which means end of the add procedure
return;
}
free(newNode);
}
int main()
{
int t,total,remain,temp;
scanf("%d\n", &t);
total = t;
trie_node* contacts = malloc(sizeof(struct node));
contacts = init(contacts);
while(t != 0){
char* s = malloc(MAX_BUF_SIZE); //char array to store the input
t--;
remain = total - t;
fgets(s, MAX_BUF_SIZE, stdin);
if (s[0] == 'a')
{
s = trim(s);
//do add operation
if (s != NULL)
{//make sure there is something to add
add(s, contacts);
}
}
else{
printf("No such operation found at line %d. (Only add or find is allowed)\n", remain);
}
free(contacts);
free(s);//memory leak problem
}
//if operation is not add or find, will be an error.
return 0;
}
Every time my program goes into the second case in add function, which is the else if statement, it will segfault saying that node->children[a[0]-97] can not be accessed.
For example, I do add abc and then add acd. This will get a segfault.
Also, I believe there is some memory leak in my function. I check my code in valgrind. It says invalid free() at free(s)
Sorry, I should mention this at beginning. a assume to be consisted of lower case letters. And all my test input for now, only consider add and find operations.