boostorg / boostorg/regex

Horrible failure mode for 'load_file' functions in test examples

Open
#274 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
119
Forks
113
PR merge metrics
No merged PRs in 30d

Description

https://github.com/boostorg/regex/blob/47d418e3f0a0e742b017199432e3f95eb8722cd8/example/snippets/regex_search_example.cpp#L87-L88

Testing `is.bad()` is almost certainly wrong, that will only be true if the fstream has encountered some I/O error or lost integrity somehow. Maybe you meant to test `is.fail()` instead? Or just `!is` which is `!is.good()` which is almost always what you should actually be testing?

Otherwise, when the fstream is not open (e.g. because `argv[1]` refers to a non-existent file) the fstream is not open, so `is.fail()` is true, and `is.good()` is false, but `is.bad()` is false because no I/O error has been encountered. The file just isn't open, that's "fail" not "bad". So the condition is false and you go to the next line, where `in_avail()` returns -1ul and you try to reserve an impossibly large number, so the program exits with:

```
Processing file /home/boost.kCe5Net2fE/BUILD/boost-1.90.0-build/boost_1_90_0/libs/regex/example/../include/boost/regex/v5/regex_iterator.hpp
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_create
```

This is extremely unfriendly. It seems like it would be much better to do something like:

```c++
void load_file(std::string& s, std::istream& is)
{
s.erase();
if(!is) throw std::runtime_error("Cannot read file");
s.reserve(static_cast(is.rdbuf()->in_avail()));
```

The `load_file` function is duplicated in loads of the files under `examples/snippets`

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with the linked load_file implementation in example/snippets/regex_search_example.cpp and then search examples/snippets for its duplicated copies. Check how each function handles an unopened or failed stream before in_avail(), and compare the other examples for consistent behavior. Done means invalid input fails with a readable error instead of attempting an enormous allocation.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
developer-experience
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.