Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any Tools to Catch Silly Mistakes in C Code?

Tags:

c

lint

findbugs

I had a nasty typo that wasted my time and my colleague's time, it was something like this:

for (i = 0; i < blah; i++); // <- I had a semi-colon here, that's the bug!
{
  // Some awesome logic here
}

First of all, it's very embarrassing, second thing, I should never repeat this. I'm relatively new to C. In Java, I guess I can use FindBugs to catch errors like these, what tool should I use for C code? Lint?

like image 331
Srikanth Avatar asked Oct 15 '08 18:10

Srikanth


3 Answers

Yes, PC-Lint is probably the best tool available.

like image 198
arul Avatar answered Oct 19 '22 22:10

arul


In addition to Lykathea's PC-Lint suggestion, you can also get better (or at least more) diagnostics if you bump up the warning level of the compiler. Something like /W4 or -Wall

Though I'm not sure if your particular problem would have been caught with this (MS VC doesn't seem to flag it even with all warnings enabled). I think that's because it's not an uncommon idiom for for loops to be empty when the work is done as side effects of the loop control expressions.

like image 42
Michael Burr Avatar answered Oct 19 '22 21:10

Michael Burr


A few things that have saved me in the past, from the top of my head:

  • Use if (3 == bla) rather than (bla == 3), because if you misspell and type (3 = bla) the compiler will complain.

  • Use the all-warnings switch. Your compiler should warn you about empty statements like that.

  • Use assertions when you can and program defensively. Put good effort into making your program fail early, you will see the weaknesses that way.

  • Don't try to circumvent any safeguards the compiler or the OS have put in place. They are there for your ease of programming aswell.

like image 4
mstrobl Avatar answered Oct 19 '22 20:10

mstrobl