# pset5 tries “Segmentation fault”

My load function crashes my program. :( I use nodes similar to instruction video:

``````// node of tries
typedef struct node {
bool wordEnd;
struct node* next[27];
} node;

// root of the tries
node* root;
``````

My function adds word stored in word[length] to tries. But it prints "Segmentation fault (core dumped)" after 3 words are added. Plese tell me what did I do wrong. I'm becoming desperate.

``````  node * tmp = root;

for (int i = 0; i < length; i++)
{
int k = word[i] - '\'';
if ( tmp->next[k] == NULL)
{
tmp->next[k] = calloc (1, sizeof(node));
if (tmp->next[k] == NULL)
{
error = true;
return;
}
}

tmp = tmp->next[k];
}
tmp->wordEnd = true;
``````

You've got the basic concept started, but the logic has some problems. First and foremost, look at `int k = word[i] - '\'';` This statement subtracts decimal 39 from the letter. Yes, you can do math on chars like this, but there's a problem. It will sorta work for "A", but will blow up for any other letter, upper or lower case. Let's take "B" as an example. 'B' - '\'' = 66 - 39 = 27. Or 'z'... 122 - 39 = 83.

Your array, temp->next[k] only goes from 1 to 26. You're accessing memory way out of the allocated range. What will happen when you try to access temp->next[any k >26]? That's why it's getting a seg fault. You need to revise the logic to something else, but you're on the right track.

Some questions for you, because while I see some issues, I don't want to just throw the answer your way.

1. Why are you subtracting '\''? Why not something like 'a' or 'A'?

2. Are you treating '\'' in a word as a special case, or trying to handle it in the same code that handles letters?

3. How are you handling upper case vs. lower case letters? Is there a way to process them both in the same block of code? are there any c functions that would make this easy, that would make upper case and lower case look the same?

4. I see the two lines `error=true;` and `return;` in your code. Are you returning from a function call? Are you trying to return a value? Maybe that should be something like `return success;` where success is a bool that says true or false?

I tried to answer your specific question. If you're satisfied that it has been answered, please mark the question as answered. If not, comment further. Let's keep up the housekeeping on this forum. :-) If you have new questions, maybe a new topic is in order?

• My bug was basically wrong reading of ASCII table. I used to think that '\'' comes one symbol befor which is "grave accent" according to wikipedia. – Filip Apr 18 '15 at 13:40