llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.61k stars 11.82k forks source link

clang/C++: issue warning when iterators from different variables are compared #5439

Open edwintorok opened 15 years ago

edwintorok commented 15 years ago
Bugzilla Link 5067
Version trunk
OS Linux
CC @DougGregor,@AnnaZaks,@gribozavr

Extended Description

Consider following program, where neither gcc, nor clang emits any warnings:

include

typedef std::vector ivect; int foo(ivect &x, ivect &y) { int sum=0; for (std::vector::iterator I=x.begin(), E=y.end(); I != E; ++I) { sum += *I; } return sum; }

This program will crash when dereferencing I (if either x or y is non-empty).

It is quite easy to typo the end iterator, especially when copy+pasting, it would be nice if clang could emit a warning in this case.

BTW to compile the above code I need to add an -I to clang, otherwise it doesn't find bits/c++config.h: clang x.cpp -I/usr/include/c++/4.1.3/x86_64-linux-gnu/ -c

0f73b9cf-134f-41af-a8b1-14d9f305ee95 commented 12 years ago

cloned to radar://12522707 for internal tracking

lattner commented 15 years ago

Yeah, good point.

DougGregor commented 15 years ago

This and other iterator-validity checks would be really useful. To do them well, I think they will have to be done by the static analyzer; Clang's semantic analysis doesn't have the ability to track the state (singular, dereferenceable, past-the-end) or domain (e.g., container) of individual iterators.

lattner commented 15 years ago

You can call foo(X,X)... but I agree that this is almost certainly an error.