Archive for the Tag 'valgrind'

Oct 12 2008

Posted by coen under Programming,c++

Valgrind and it’s neighbours

For some time now, I have been working om my messaging client Skaar. Last week I built a version that only can connect to an IRC-server. There’s still a lot of work to do, but it was time to test and debug my work done so far.

A classmate told me to use valgrind to test Skaar for memory leaks. Valgrind is a suite of tools for debugging and profiling programs, so that should work, and there I went:

valgrind --log-file=./valgrind.log --leak-check=full ./skaar

After shutting down, it turned out that Skaar had left something behind, and not that modest (43Kb) either. It’s actually not that simple to prevent memory leaks, I learned. The obvious cases seem to scream: free(3) or delete me, but the not so obvious cases keep their mouths perfectly shut..

Obvious case:
char* line = (char*)malloc(513);
memset(line, 0, 513);
strcpy(line, "PRIVMSG #mychannel :foo\r\n");
...
free(line);

Not so obvious case:
// in RFC1459.cpp
JoinMessage* joinmessage = new JoinMessage(this, line);
return (AbstractMessage*)joinmessage;


// somewhat later in Skaar.cpp
AbstractMessage* message = protocol->translateIncoming(rawmsg);
...
delete message;

I’m wondering if this is the right way to end the AbstractMessage*‘s life, by the way. Who’s responsibility is it to get rid of the message? I could go with this solution, that says: “Here is your object, have fun”. I could also create a function in the protocol that destroys the message, something like RFC1459::destroyMessage(AbstractMessage* message), that says “Here is your object, but you have to let me take care of it’s end. Actually, I have no clue which one is the best choice, if there is a best choice here..

But, back to business: all I have to do now is just test every possibility to see if there are any leaks. Or I could just watch it when I write code, which also sounds nice.
Another tool that I’ve come to value is gdb, The GNU Project Debugger. This tool allows you to see what happens ‘inside’ the program while it executes. And yes, I stole that line from gnu.org :)
To start using gdb is not very hard, just type gdb yourprogram, and that’s that. To actually start executing you program, type run once gdb has started.

No Comments »