What should I do to allocate memory space for pNode->data
, I want to put a single character into it, like pNode->data = "c"
. But it shows segmentation fault and the memory address for pNode->data
is 0x1
which is out of bound.
Below is my code.
typedef struct node {
char* data;
int weight;
bool end_of_key;
struct node* left;
struct node* equal;
struct node* right;
} node_t;
typedef struct listnode{
char* data;
int weight;
struct listnode* next;
} listnode_t;
node_t* insert(node_t* pNode, char* word, int weight) {
if(pNode == NULL) {
/**
* Create a new pNode, and save a character from word
*/
pNode = (node_t*) malloc(sizeof(*pNode));
pNode->left = NULL;
pNode->equal = NULL;
pNode->right = NULL;
strcpy(pNode->data, word);
}
if(*word < *(pNode->data)) {
/**
* Insert the character on the left branch
*/
pNode->left = insert(pNode->left, word, weight);
}
else if(*word == *(pNode->data)) {
if(*(word+1) == '\0') {
/**
*set pNode end_of_key_flag to true and assign weight
*/
pNode->end_of_key = true;
pNode->weight = weight;
}
else {
/**
* If the word contains more characters, try to insert them
* under the equal branch
*/
pNode->equal = insert(pNode->equal, word+1, weight);
}
}
else {
/**
* If current char in word is greater than char in pData
* Insert the character on the right branch
*/
pNode->right = insert(pNode->right, word, weight);
}
return pNode;
}