Debugging Code in C/C++

What to do when your C/C++ code has problems? How to debug it?

Well, this is exactly the problem I am trying to help you with. Sometimes, (read always) debugging the code can be quite frustrating. There are times you don’t know exactly what is causing the problem and that alone can make you question your programming skills.

Approach to Debug the Code

There are two approaches to debug the code that I can think of. 

  1. Using Logs
  2. Using Debugger

Using Logs

Well, you can use logs. What I mean by that is you can use print statements in various parts of the code and that can help you take down the bugs.

Although this technique will help you in debugging the smaller project, this is certainly not practical in debugging the projects with thousands of files. A little better strategy you can use here is you can attach the level of debug message along with the logs. These levels could be- info, warning, error, etc. You can also attach the file name or maybe “class name” alongside the debug message and the logs. You can create a small function that accepts the level of logs(Log Level), your unique name(Log Group that you want to give), and log message as a function parameter and prints all of that together in the console. Use that function as a Log instead of using a simple printf function.

Another thing you can do is to make log a memory address of a pointer(along with the pointer name of course) after allocating the memory using malloc or calloc. This little trick can help you track down the memory leaks that can be there. Similarly, you can log the pointer name before using the free function.

Using Debugger

Well, this is another strategy to debug. I like this one better than using logs. But it might be an overkill to use the debugger for small projects.

This technique is certainly better than using logs because of the following reasons:

  1. Well for starters, you don’t need many logs, to begin with.
  2. The ability to pause the program at the given point of time.
  3. You can backtrace the entire flow of the program.
  4. Using breakpoints, you can easily find out the location where the problem is.
  5. The Debugger lets you know the value of instances and variables at the given point of time in the program. 

There are many more advantages of using debugger but I think this is enough. In the next article, I am going to write about how you can set up the debugger in your machine and use it. 

Leave a Comment

Your email address will not be published. Required fields are marked *

Share This