-10

Valgrind is finding memory leaks but i can't seem to pinpoint them, i'm hope-full someone here can help me:

enter image description here

enter image description here

main calls are Dictionary* dictionary = initDictionary();

Nix
  • 77
  • 1
  • 10
  • 7
    Don't post images of code – klutt Jan 15 '20 at 08:27
  • 2
    Also [don't cast malloc](https://stackoverflow.com/q/605845/6699433) – klutt Jan 15 '20 at 08:28
  • 1
    And in the future, please try to create a [mcve] that replicates the problem, and show it to us. And please read about (or refresh) [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Jan 15 '20 at 08:31
  • 1
    I wonder why your compiler does not issue any warning that your `initDictionary` does not return a pointer as declared. What does your main look like? If you ever do an `Dictionary *d = initDictionary()` , the compilation should fail (unless you run into your failure conditions in the method itself, causing it to return `0`). So I suspect there is something fishy in your main as well... – Michael Beer Jan 15 '20 at 08:33
  • @MichaelBeer Yeah i can't believe i missed that, definitely an embarrassing post. Never the less not only does it not provide a compile error, the output is correct. This is a part of a college assignment and the automatic test passed it. – Nix Jan 15 '20 at 08:56
  • @klutt & some programmer dude will do, sorry for the silliness – Nix Jan 15 '20 at 08:58
  • 1
    @Nix nothing embarrasing about it. I know situations like these quite well, errors like that happen to everyone, no matter how experienced. The compiler might not issue warnings unless you tell it to because not returning a value is standard compliant unless you want to read the return value. Anyhow, since you get no compiler error, it looks to me that you do not use the return value in your main anyhow, and that's certainly not what you want... – Michael Beer Jan 15 '20 at 09:00
  • 2
    Compile with `-Wall -Wextra` – klutt Jan 15 '20 at 09:01

1 Answers1

5

Your initDictionary doesn't return the pointer dictionary anywhere.

That means when you do

Dictionary* dictionary = initDictionary();

the value of dictionary will be indeterminate (seemingly random or garbage), and dereferencing this pointer or passing it to free will result in undefined behavior.

You solve this by adding a simple

return dictionary;

at the end of the initDictionary function.


If your compiler doesn't warn you about not returning anything from the function, you need to enable more verbose warnings. Using gcc or clang I recommend the options -Wall -Wextra -Wpedantic when building. For MSVC use /W4.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621