llvm-project
llvm-project copied to clipboard
False positive with vector reserve
So, code
#include <vector>
int main()
{
std::vector<int> v;
v.reserve(2);
v.push_back(1);
auto it = v.begin();
v.push_back(2);
return *it;
}
gives a warning
<source>:9:13: warning: passing a dangling pointer as argument [-Wlifetime]
return *it;
^
<source>:8:5: note: modified here
v.push_back(2);
while v is guaranteed not to reallocate.
I used compiler on godbolt.
clang version 7.0.0 (https://github.com/mgehre/clang 4385bf94e655affaf1555bfbde3ccbb5c16c3ee8) (https://github.com/llvm-mirror/llvm d8e175bca5919de13fe003cab6b10f23af3d055d)
The similar example with std::set
#include <set>
int main()
{
std::set<int> v;
v.insert(1);
auto it = v.begin();
v.insert(2);
return *it;
}
Hi Alexey,
thank you very much for taking the time to report your findings. For your first examples (std::vector) the lifetime paper provides no means to suppress the warning. reserve is not considered and push_back is always considered to reallocate. I can talk to Herb about this, but I don't see an easy way out.
For your second example, the std::set, the paper correctly says that std::set::insert will not invalidate iterators, but our implementation is currently missing the correct annotations. This bug will be fixed in the implementation.
I think reserve should be considered to reallocate (as it does now) because it actually reallocates most of the time(you don't call to reserve if you don't expect it to reallocate)
Note that the set example should be fixed in https://github.com/mgehre/clang/commit/9a538958ac210964bb5f141b4aee45c5fceaccea