Thursday, February 2, 2012

Frustration With Memory Management

Well, this might be slightly unrelated to "object-oriented programming", but the issue still applies to C++ and is applicable to the nature of this blog. I have just finished my first real project in C, and while not it was not in Professor Downing's class, it taught me a good deal about memory management. The project involved creating a list of sorted point "objects" (which were really structs), and to my eyes it seemed the idea lent itself well to the creation of a linked list data type. The sorted point structure would hold a pointer to the head of the list and the number of elements in the list. It seemed simple enough, but creating linked lists in a safe language like Java and trying to apply the same concepts to C do not completely work. C (and C++) will not simply throw away the nodes in the list when they are removed. Instead, they will sit there until the code tells them that they are free and available for use again. The main problem I had was that the sorted point structure was being allocated twice in the heap: once in the tester file and once in the sorted point init function. While it took much longer than it should have to find the bug, I gained some knowledge on some tools that we have used in 371p and some that I am positive I will be using. For the former I am referring to Valgrind, the utility which essentially yelled at all of my lost blocks of memory. While sometimes the information it gives can be a little ambiguous, it is definitely correct, and it can make you feel like an idiot even though your code might be producing the correct output. I will say that seeing the following three lines can be a huge sigh of relief when debugging code:


definitely lost: 0 bytes in 0 blocks
indirectly lost: 0 bytes in 0 blocks
possibly lost: 0 bytes in 0 blocks

Speaking of debugging, I had a first-time experience with another tool today: GDB, the GNU Project Debugger. It is a very cool utility that allows you to trace through your code, step through functions, see the stack trace, set new values to variables, set breakpoints, show the values of variables at any time, and much more. I mainly used it with the -tui flag which pulls up a nice interface in the terminal that will show you where you are in stepping through the code. While debugging is never a fun task, it was interesting getting to use such a real debugger for the first time.

Memory Management is a beast that demands perfection from the person writing the code. There is no room for mistakes and no place for slackers.

No comments:

Post a Comment