Clang Analyzer – A Great Cross-Platform C Static Analyzer

Clang Analyzer is a Static Code Analyzer for C and Objective-C.

Why it’s great:
1. It works on Mac, and Linux.
2. Running it is as easy as:

scan-build -V gcc -o prog prog.c

or

scan-build -V make

3. It gives great looking HTML reports.

4. You can easily report all or part of the errors as bugs:


Note (If you’re using Xcode):
Clang is built-in Xcode as of version 3.2. Run “Build and Analyze” to analyze your programs.


Define A Macro In C With A Variable Number Of Arguments

Say you want to wrap a function like printf() (which receives a variable number of arguments) with a macro. This is how to do it:


#define PRINT_DEBUG(fmt, args...)  printf("DBG:"fmt, ##args)

That is, declare them as args… and use them with ##args.

Note: The word args has nothing special, you could similarly use somethingelse… and ##somethingelse. Just in case you were wondering ;-)

Finding The Median Of Two Sorted Arrays

The reason I’m writing about this problem, is not because of this specific problem itself, but because it shows that sometimes it’s simpler to solve a more general problem, where the original problem is a private case, and then applying the solution to this private case.

Maybe this is counterintuitive at first: How can happen that solving the general case is simpler? As engineers, we’re used to think in the terms of trade-offs, either you solve a general problem (win) with great effort (lose), or you solve a private and specific case (lose) with little effort (win). It doesn’t feel right to win twice: Both solve the more general problem, and do it with less effort.

This intuition seems to not always be correct, as in the case we’re discussing here. Moreover, many times, understanding a more general problem gives a better insight into the nature of the problem than a private case.

The message I’m trying to pass in this article, is: If you’re facing a problem, and something in the problem feels too constrained, don’t hesitate to think of a more general problem, by relaxing some constraints and unbinding parameters.

Let’s dive into our specific problem:

Continue reading →