[英]Segmentation Fault in a BST of strings
So, I'm doing an assignment for a class in college and the objective is to construct a BST of strings that read a text, divides it and insert each word in the Tree. 因此,我正在为某大学的一堂课做作业,目的是构造一个字符串的BST,该字符串读取文本,将其划分并将每个单词插入树中。
But I'm getting a segmentation fault when trying to insert a word (manually), can you guys show me where I did wrong and suggest a repair? 但是,尝试手动插入一个单词时遇到了段错误,你们可以告诉我我做错了什么并建议修复吗?
/* Structure for the node */
typedef struct node {
char *key;
int multi;
struct node *left, *right;
} node;
node *root;
void Insert(char *x, node *p){
p = root;
/* if the pointer points to null, create a new node and insert the key */
if (*p == NULL){
(*p) = (node)malloc(sizeof(node))
(*p)->key = strcpy((*p)->key, x);
(*p)->left = NULL;
(*p)->right = NULL;
return;
}
else if (strcasecmp(x, p->key) < 0)
{
Insert(x, &p->left);
return;
}
else if (strcasecmp(x, p->key) > 0)
{
Insert(x, &p->right);
return;
}
/* if the words are equal, add 1 to the multi (how many times the word appears */
else
(*p)->multi = multi + 1;
}
This is the problematic statement: (*p)->key = strcpy((*p)->key, x);
这是有问题的语句:
(*p)->key = strcpy((*p)->key, x);
You allocated memory only for node
but the pointer key
is still uninitialized. 您仅为
node
分配了内存,但指针key
仍未初始化。 You need to allocate memory for key
also, something like (*p)->key = malloc(strlen(x) + 1);
您还需要为
key
分配内存,例如(*p)->key = malloc(strlen(x) + 1);
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.