Opened 4 years ago
Closed 4 years ago
#11147 closed defect (fixed)
FP invalidContainer with substr()
| Reported by: | chrchr | Owned by: | pfultz2 |
|---|---|---|---|
| Priority: | Normal | Milestone: | 2.9 |
| Component: | False positive | Version: | |
| Keywords: | invalidContainer | Cc: |
Description
From solvespace-3.1-rc1/src/util.cpp:
void f(std::string& s) {
if (!s.empty()) {
std::string::iterator it = s.begin();
while (isspace(*it)) it++;
s = s.substr(it - s.begin());
}
}
test.cpp:5:22: error: Using iterator to local container 's' that may be invalid. [invalidContainer]
s = s.substr(it - s.begin());
^
test.cpp:1:22: note: Passed to reference.
void f(std::string& s) {
^
test.cpp:3:43: note: Iterator to container is created here.
std::string::iterator it = s.begin();
^
test.cpp:4:23: note: Assuming condition is false
while (isspace(*it)) it++;
^
test.cpp:5:11: note: After calling 's=s.substr(it-s.begin())', iterators or references to the container's data may be invalid .
s = s.substr(it - s.begin());
^
test.cpp:1:21: note: Variable created here.
void f(std::string& s) {
^
test.cpp:5:22: note: Using iterator to local container 's' that may be invalid.
s = s.substr(it - s.begin());
^
Tested with https://github.com/danmar/cppcheck/commit/60c1eef6592f7ed49ccc2412923cc7ea9f04c67d.
Change History (4)
comment:1 by , 4 years ago
comment:2 by , 4 years ago
| Milestone: | → 2.9 |
|---|---|
| Owner: | changed from to |
| Status: | new → accepted |
comment:4 by , 4 years ago
| Resolution: | → fixed |
|---|---|
| Status: | accepted → closed |
Note:
See TracTickets
for help on using tickets.
This also shows the error:
void f(std::string& s) { if (!s.empty()) { std::string::iterator it = s.begin(); s = s.substr(it - s.begin()); } }This is clean:
void f(std::string& s) { if (!s.empty()) { std::string::iterator it = s.begin(); auto t = s.substr(it - s.begin()); s = t; } }