views:

126

answers:

3

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 ); it != 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?

+1  A: 

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.

Timo Geusch
A: 

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.

Goz
A: 

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;
}
Mike D.
iek! rewrite perfect code to match the output of the tool?
xtofl
Well, the tool doesn't think it's perfect. And I have to wonder what an iterator's `operator++` needs `it._M_current` for. It boils down to: 1) find a way to tell the tool that that "error" is OK, or 2) rewrite the code to do the same thing but in one more line, or 3) ditch the tool. I'm not seeing a better answer here, sorry.
Mike D.