Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code coverage (c++ code execution path)

Let's say I have this code:

int function(bool b)
{
    // execution path 1
    int ret = 0;
    if(b)
    {
        // execution path 2
        ret = 55;
    }
    else
    {
        // execution path 3
        ret = 120;
    }
    return ret;
}

I need some sort of a mechanism to make sure that the code has gone in any possible path, i.e execution paths 1, 2 & 3 in the code above.

I thought about having a global function, vector and a macro.
This macro would simply call that function, passing as parameters the source file name and the line of code, and that function would mark that as "checked", by inserting to the vector the info that the macro passed.

The problem is that I will not see anything about paths that did not "check".
Any idea how do I do this? How to "register" a line of code at compile-time, so in run-time I can see that it didn't "check" yet?

I hope I'm clear.

like image 551
Poni Avatar asked Jun 01 '10 00:06

Poni


People also ask

What is code path coverage?

Path Coverage A code path is the execution of the module's entry point to the exit point. Path coverage is more complicated than statement and branch coverage because the code may contain an unlimited number of paths.

What is code coverage in C?

Introduction. Code coverage measures the number of lines of source code executed during a given test suite for a program. Tools that measure code coverage normally express this metric as a percentage. So, if you have 90% code coverage then it means, there is 10% of the code that is not covered under tests.

How do you show code coverage?

Code coverage option is available under the Test menu when you run test methods using Test Explorer. The results table shows the percentage of the code executed in each assembly, class, and procedure. The source editor highlights the tested code.


2 Answers

Usually coverage utilities (such as gcov) are supplied with compiler. However please note that they will usually give you only C0 coverage. I.e.

  • C0 - every line is executed at least once. Please note that a ? b : c is marked as executed even if only one branch have been used.
  • C1 - every branch is executed at least once.
  • C2 - every path is executed at least once

So even if your tests shows 100% C0 coverage you may not catch every path in code - and probably you don't have time to do it (number of paths grows exponentially with respect to branches). However it is good to know if you have 10% C2 or 70% C2 (or 0.1% C2).

like image 193
Maciej Piechotka Avatar answered Oct 14 '22 04:10

Maciej Piechotka


Quite often there will be a utility supplied with your compiler to do this sort of code coverage analysis. For example, GCC has the gcov utility.

like image 2
Greg Hewgill Avatar answered Oct 14 '22 04:10

Greg Hewgill