Deleting data allocated in node

Hi, I'm trying to create unbalanced binary tree but after I'm done using it I'm having some real problems deleting the char* that was allocated using strdup C function. I'm always getting some error
Invalid address specified to RtlValidateHeap( 00530000, 00551AF8 )
exercise_6_2.exe has triggered a breakpoint.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node{
	int count;
	char* word;
	struct node* left;
	struct node* right;
};

struct node* add_node_to_tree(struct node* root, char* word)
{
	if (root == NULL) {
		root = (struct node*)malloc(sizeof(struct node*));
		root->count = 1;
		root->word = strdup(word);               //strdup here
		root->left = root->right = NULL;
	}
	else if (strcmp(word, root->word) < 0)
		root->left = add_node_to_tree(root->left, word);
	else if (strcmp(word, root->word) > 0)
		root->right = add_node_to_tree(root->right, word);
	else
		++root->count;

	return root;
}

int main()
{
	struct node* n = NULL;
	n = add_node_to_tree(n, "Hello World!\n");

	printf("word added = %s\n", n->word);  //prints Hello World!
	free(n->word);                         //breakpoint triggered here

}
Last edited on
http://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c

If strdup is not in standard C and you run in Windows, then whose extension do you use?
You could try self-written strdup for comparison.
Hi, Tnx for reply. I was actually using my own version (exactly like the one in the link you gave me) of it after the original failed but it still gave me the same behavior.

Its interesting that this on the other hand is working
1
2
3
4
	struct node* p = (struct node*) malloc(sizeof(struct node*));
	p->word = str_duplicate("another test");
	printf("p->word = %s\n", p->word);
	free(p->word);
Last edited on
Ok so I found the error, 2 hours of my life is gone but its ok :D

line 15
root = (struct node*)malloc(sizeof(struct node*));
Allocated space only for node* not node itself :D Tnx for showing interesting in this thread :)
Last edited on
Topic archived. No new replies allowed.