开发者

STL iterator - why is the code analysis tool complaining?

开发者 https://www.devze.com 2022-12-13 11:27 出处:网络
I\'m checking the results from the static code analysis tool Klocwork. It complains about the following code:

I'm checking the results from the static code analysis tool Klocwork.

It complains about the following code:

293 for( my_vector_typedef::iterator it( start_pos ); i开发者_如何学运维t != end_pos ; ++it ){
294   delete *it;
295 }

With the following message:

Object 'it._M_current' is used after it was freed. Object 'it._M_current' was used at line 293 after being freed by passing argument 1 to function 'delete' at line 294

I know things (especially iterators) in STL sometimes aren't really what they seem so I would like to understand what goes on. Purposely formulating the question silly - The 'delete' is performed on what 'it' is pointing at, and not 'it' itself, so why would it complain about it being used with '++it'? It's not it that has been deleted?


That looks to me like the tool is a little confused by the fact that you're trying to delete the object referenced by the iterator it. ++it should simply reload _M_current with its new value, but this seems to confuse the tool.

It doesn't look particularly dangerous to me so I'd be tempted to see if you can disable this warning. Usually with static analysis tools you'll have to tweak them a little to match your coding style.


It looks to me that the code analysis tool doesn't understand dereferencing well. I've never seen a perfect code analysis tool. Most have errors of some sort. If the code looks fine after you've checked, double-checked and triple-checked it probably is and the code analysis tool is wrong.


You could rewrite your loop to increment it before the delete:

my_vector_typedef::iterator it( start_pos );
while(it != end_pos)
{
    type_used_in_my_vector* x = *it++;
    delete x;
}
0

精彩评论

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