1

When I use this

valgrind --leak-check=yes ./Main

I have about 185236 errors. It said that:

xx bytes in x blocks are possibly lost in loss record xxxx of xxxx

Here's my code:

Node InsertString(Head head, Node tree, char* data) {
    if (tree == NULL) {
        tree = malloc(sizeof (struct TreeNode)); //Error

        if (tree == NULL) {
            printf("Out of Space!\n");
        } else {
             tree->theData = malloc(sizeof (char) * strlen(data));//Error
            strcpy(tree->theData, data);
        }
    } else {
            if (strcmp(data, tree->theData) < 0) {
                tree->Left = InsertString(head, tree->Left, data); //Error
            } else {
                if (strcmp(data, tree->theData) > 0) {
                    tree->Right = InsertString(head, tree->Right, data);//Error
                }
            }
        } 

    }
    return tree;
}

Thank you!

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Tuan
  • 13
  • 2

2 Answers2

4

Do you ever call free to deallocate the memory you are allocating with malloc?

If not, well, then you're leaking all that memory.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • Hi thanks for replying me, Can you explain to me why we have to malloc for a memory space to store data and then we free it? – Tuan Dec 28 '10 at 05:15
  • 2
    @Tuan: It would behoove you to obtain [a good beginner C book](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). I cannot sufficiently explain the C memory model and best practices for dynamic allocation in C in the short space available for this answer. – James McNellis Dec 28 '10 at 05:17
-2

Use a tool called valgrind. It will tell you of such memory leaks.

user555615
  • 27
  • 4