I am developing a software that use BST (Binary Search Tree), but i don't understand what's going on:
while (1)
{
word = (char *)malloc(sizeof(char) * wordLength);
readReturn = scanf("%s", word);
if (readReturn == 0)
return 0;
BSTNode new = newBSTNode(word);
if (strcmp(word, "END") == 0)
break;
TreeInsert(Tree, new);
}
In this way the program it's working and give the input "aaa" "bbb", the tree has the right value. But if i declare the variable outside the program stop working and the output is: "bbb" "bbb".
word = (char *)malloc(sizeof(char) * wordLength);
while (1)
{
readReturn = scanf("%s", word);
if (readReturn == 0)
return 0;
BSTNode new = newBSTNode(word);
if (strcmp(word, "END") == 0)
break;
TreeInsert(Tree, new);
}
Please, explain me why this is happening!
In the second code snippet
word = (char *)malloc(sizeof(char) * wordLength);
while (1)
{
readReturn = scanf("%s", word);
if (readReturn == 0)
return 0;
BSTNode new = newBSTNode(word);
if (strcmp(word, "END") == 0)
break;
TreeInsert(Tree, new);
}
all strings are stored in the same dynamically allocated extent of memory that was allocated once before the while loop.
word = (char *)malloc(sizeof(char) * wordLength);
So all nodes refer to it and what was stored last in this extent is outputted for all nodes.
Pay attention to that in the first code snippet
while (1)
{
word = (char *)malloc(sizeof(char) * wordLength);
readReturn = scanf("%s", word);
if (readReturn == 0)
return 0;
BSTNode new = newBSTNode(word);
if (strcmp(word, "END") == 0)
break;
TreeInsert(Tree, new);
}
there can be a memory leak if after the loop there is no statement
free( word );