I have implemented a binary heap as a tree, and tree node is as follows;
struct tree_node {
char* p_word;
int count;
struct tree_node* parent;
struct tree_node* p_left;
struct tree_node* p_right;
};
Everything works perfectly until it comes to the char* member. When I try to allocate some memory space for p_word, i am given ‘Segmentation Fault’ in the runtime.
fgets(buffer, BUFFERSIZE, fp);
for(tok = strtok(buffer, " "); tok; tok = strtok(0, " ")) {
if(tok) {
curr = (lpnode)malloc(sizeof(node));
curr->p_left = curr->p_right = NULL;
curr->count = 1;
curr->p_word = (char*)malloc(sizeof(char) * strlen(tok));
strcpy(curr->p_word, tok);
insert(&root, &root, curr);
}
}
fclose(fp);
Note that, curr represents the node which is going to be added to the tree and root represents the tree’s root node.
How can I overcome this problem without causing any memory leak?
Ah finally I solved it; the problem was inside of insert function. I found out that I had been trying to convert integer parameter to the char pointer. This is a debugging failure, shame on me 🙂 Anyway, thank you all guys.