开发者

Confusing control flow analysis from Parasoft C++test

We use Parasoft C++test to statically analyze our code. It's having trouble with code like the following:

void foo(int* x) {
    try {
        bar();
    } catch(...) {
        delete x;
        throw;
    }

    *x;
}

It warns on the *x; line that:

Freed memory shouldn't be subsequently accessed under any circumstances

Somehow it's concluded that control flow can pass into the catch(...) block, delete x, go past the throw;, and make it to *x;. I tried throw std::exception(""); and a couple others and got the same thing. Parasoft certainly knows about exceptions and incorporates them into its control flow, because there are many other tests that involve exception checking. Is it just confused in this case, or is there actually some way for the execu开发者_如何学运维tion of this program to hit both delete x; and *x;?


So the tool is wrong (It's been said before, I know), and I assume you dont want to swith of the warning.

I agree with @Pascal's comment that it is somewhat dangerous to rewrite code just to work around some tool's limitiations. What you can do is disable this warining for just the files where you currently have this problem.

Then, you have a warning free build to begin with, without a tool telling to rewrite existing valid code.

For new code, you will have to adopt some style that's understood by the tool. This is less of an issue because that will be code you currently work on, so it would be less of an issue if you need to rewrite it slightly to get rid of warnings.

Although correct, the existing style is far from ideal.

I would reccomend storing pointers like x in auto_ptr's. That will automatically delete the content of the auto_ptr if it goes out of scope - unless you explicitly take it out of the auto_ptr. This is a lot easier on the eyes, and also nicely documents that this function takes ownership of the pointer.

void foo(auto_ptr<int> x)
{
    bar();
    *x;
}

I would expect ParaSoft will have no problems with this code.


Perhaps this is a daft suggestion, but what does Parasoft say if you leave the catch for the end? I.e.

void foo(int* x) 
  {
  try 
    {
    bar();
    *x;
    } 
  catch(...) 
    {
    delete x;
    throw;
    }      
  }

I realize that may not work for all combinations of statements and exceptions, for example if you have multiple exception types to catch with different handling at different stages of foo, but at least it may give you the start of a workaround if you really want to get rid of the warning.


Quick update:

1) The above mentioned rule is not a flow analysis rule at all. That being said, the rule (ID MRM-31) was improved in C++test 9.2.0 and later. There is also a corresponding flow analysis rule for this in C++test (ID: BD-RES-FREE) that should do what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜