I'm not sure if my unload() function worked properly. I tried to use Valgrind and it said memory leaked 8mb. I tried check50 and it said I have a memory leak.

enter image description here

Also, the time takes very long, it takes 5sec in total, to finish the program. enter image description here

This is the code on 75, where I malloc a next_node, but I don't know where I should free them enter image description here

1 Answer 1


What makes you think that the problem lies with unload? What's your thought process that leads you there? Or did you jump to that conclusion because that's where all the freeing is done? (Teachable moment question.)

Valgrind is telling you that the memory that's being leaked is being allocated on line 75. What's happening to that memory as the program proceeds?

The memory leak has nothing to do with unload. Look at lines 75 and 76. Line 75 does two things. It creates a pointer AND it allocates memory to that pointer. Then, line 76 reassigns new_node, making it point at something else. This essentially abandons the memory that was allocated on line 75. That's called a memory leak. Memory is allocated and then abandoned without being freed.

Easy fix. Instead of a malloc on line 75, assign NULL to the pointer to initialize it. Better still, combine lines 75 and 76.

node *node_next = hashtable[hashIndex];

As for taking 5 seconds to finish the program, well, that's an entirely different exercise. If you want to make it run faster, you need to look at the entire design and look for ways to make it more efficient. That's a good exercise and learning opportunity for you! Besides, how do you know that 5 seconds is too long?

Finally, you may or may not find other issues that still remain, but those are for another question. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • I fixed it and you made me think even further. I jumped to the conclusion because unload is where I have done all the freeing. I appreciated and I will learn from the mistakes. However, is there any hints or ways I should do to make my program run faster and more efficient? How should I improve my design?
    – Jn Wu
    Jun 29, 2019 at 4:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .