Saturday, June 14, 2014

Free From Memory

Another check in, the past few months I set off to remove all memory leaks from hero quest, using Valgrind (or more specifically, mem-check). However, I encountered this:
"At one end of the scale, Memcheck adds code to check every memory access and every value computed, making it run 10-50 times slower than natively."
One of the memory intensive things with most games is loading images or textures. As the character selection screen loaded the same images multiple times, whenever I was trying to free memory around there, I had to wait approximately 5 seconds for the screen to load. If you choose "VS Mode" in any computer game, you expect it to load the character selection screen instantly; 5 seconds is a long time.

This prompted me to add a caching layer on top of my image loading. However, my coding skills at the time of writing the graphics component were not at a level that enabled me to produce extensible code. So, I spent a few months doing the following:

  • Replacing SDL 1.2 with SDL 2.0 (SDL 2.0 was released)
  • Rewriting the graphics component from scratch
  • Updating existing code to use the rewritten graphics component
  • Finding memory leaks, and fixing them (if possible*)
* some leaks were detected in SDL and system libraries, I did not fix these

I'm happy to say the final result of this is the following Valgrind report:
==4498==
==4498== HEAP SUMMARY:
==4498==     in use at exit: 56,314 bytes in 469 blocks
==4498==   total heap usage: 129,540 allocs, 129,071 frees, 519,910,160 bytes allocated
==4498==
==4498== LEAK SUMMARY:
==4498==    definitely lost: 0 bytes in 0 blocks
==4498==    indirectly lost: 0 bytes in 0 blocks
==4498==      possibly lost: 0 bytes in 0 blocks
==4498==    still reachable: 55,998 bytes in 460 blocks
==4498==         suppressed: 316 bytes in 9 blocks
==4498== Reachable blocks (those to which a pointer was found) are not shown.
==4498== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==4498==
==4498== For counts of detected and suppressed errors, rerun with: -v
==4498== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 6)

What's next:

  • Launching a game instance with selected characters (including assigning an ai controller)
  • Maps / backgrounds
  • Interaction between characters


1 comment:

  1. Woho! Interesting! I really should give that Valgrind a go. I never really paid THAT much attention to memory leaks (most probably because I am not yet aware of what they can cause; imma give it a read later). It's rather amazing how you had your code cleaner than the official libraries and APIs you're using.
    Btw, do you use OpenGL for rendering or SDL 2.0 (since that supports textures and HW acceleration now) ?

    ReplyDelete