Reputation: 9
Im currently running into an issue where I have to input words (strings) into a binary search tree and am doing so by putting words(strings) into string arrays, however when I try to put it into the first element, it is segmentation faulting.
Here is what I have:
node.h
typedef struct Node{
char letter;
int asiccValue;
struct Node *left, *right;
string words[99];
int wordCount;
}Node;
tree.cpp
// This function creates new nodes as needed
Node *createNode(string word){
// Assigns values
struct Node *temp = (Node*)malloc(sizeof(Node));
temp->letter = word[0];
temp->asiccValue = (int)word[0];
temp->left = NULL;
temp->right = NULL;
temp->words[0] = word;
temp->wordCount = 1;
return temp;
}
Upvotes: 0
Views: 136
Reputation: 7863
malloc
doesn't call constructors, meaning your string
array isn't initialized. For any non-trivial type, you really want to avoid malloc
unless you know what you're doing (see also: placement new
).
Using new
should fix your problem. Make sure you update existing code to use delete
instead of free
. Also, consider getting rid of new
/delete
entirely, and using make_unique
and friends.
Node *createNode(string word){
// Assigns values
Node * temp = new Node;
temp->letter = word[0];
temp->asiccValue = (int)word[0];
temp->left = NULL;
temp->right = NULL;
temp->words[0] = word;
temp->wordCount = 1;
return temp;
}
Upvotes: 1