Testing for memory leaks in C

Whilst wandering round the Cambridge University bookshop the other weekend, I noticed a book called Memory as a Programming Concept in C and C++. It was just too tempting, so I bought a copy.

Nobody has ever taught me about memory management in C, I've worked this stuff out from experience and probably by reading other peoples code. So it's nice to read a tutorial - even if I've already been doing this stuff for years. If nothing else, it's made me think more carefully before I dynamically allocate some memory. And I thought that I was pretty careful in the first place.

So I decided to write some debug code to test for memory leaks in my H2D2 virtual machine. I was pretty confident I would not find any problems. But, I did actually find a calloc() where I had meant to put a realloc(). A silly mistake where I wasn't being careful enough. This was leaking memory, because I had a malloc() which was being followed by a calloc() instead of realloc() - so the memory allocated in the first place was not getting freed up (only the memory from the calloc() was getting freed up).

Here is an example of the debug code that I've written: view C code (as a text file).

You just need to replace your calls to malloc, calloc, realloc, and free with rmalloc, rcalloc, rrealloc, and rfree. As you can see from the code, it simply maintains an array of pointers to dynamically allocated memory, so when your code exits you can see if there are any 'dangling' pointers left over. Simple, but effective. If there are no pointers left when your code finishes then you're probably not leaking memory. Nice.

Anyway, I'd be happy to recommend the book 'Memory as a Programming Concept in C and C++', I've found it a useful recap on many things and a good reminder to be extra careful with dynamic memory. It's also been fun to write some memory debugging code, which is a tangent that I may not have gone down if I had not bought the book. Although this book was published 9 years ago, it's nice to see a good book on C programming that's less than a decade old. Thanks Frantisek!

DEC PDP-11/53: New CPU Board

The chap who sold me some of the PDP parts was kind enough to let me try another KDJ11-D CPU board that he had, since I thought that the RAM was dead on the first one.  Here it is:

New CPU Board

This one works!  Well, in reality it also has issues ... if I try to use all 1.5 Mb of RAM it also fails the self-test on startup.  So I tried setting the W25 jumper as documented here.  With that jumper in place it seems to work fine, although it means that I'm limited to 512k of memory.  So I imagine that the problem must be in the upper megabyte.  It would seem that these old RAM chips have a tendency to die.  However, it should be good enough for me to continue moving forward.  Although at some point it would be nice to have a fully working KDJ11-D (M7554) in my machine.  I must keep an eye out for that.