boostorg / boostorg/range

Indexing operator of iterator_range<counting_iterator<...>> produces undefined behavior

Open
#83 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
45
Forks
104
PR merge metrics
No merged PRs in 30d

Description

Example:

```c++
#include
#include

#include
#include

int main(int, char **)
{
using iterator = boost::counting_iterator;
using iterator_range = boost::iterator_range;

iterator first(0), last(3);
iterator_range range(first, last);

std::cout << "iterator::reference is a reference type: " << std::is_reference::value << std::endl;
std::cout << "iterator_range::reference is a reference type: " << std::is_reference::value << std::endl;

std::cout << "first[0] returns a reference type: " << std::is_reference::value << std::endl;
std::cout << "range[0] returns a reference type: " << std::is_reference::value << std::endl;

std::cout << "first[0] == " << first[0] << std::endl;
std::cout << "range[0] == " << range[0] << std::endl; // <-- segfault
}
```

Output:
```
iterator::reference is a reference type: 1
iterator_range::reference is a reference type: 1
first[0] returns a reference type: 0
range[0] returns a reference type: 1
first[0] == 0
Segmentation fault (core dumped)
```

Expected behavior: `range[0]` returns `0`.

If Boost headers are copied to `./boost` and the program is compiled with g++ `-I.` option, the compiler produces the following warning:
```
In file included from ./boost/range/iterator_range.hpp:13,
from test_counting_iterator_range_indexing.cpp:2:
./boost/range/iterator_range_core.hpp: In instantiation of ‘boost::iterator_range_detail::iterator_range_base::reference boost::iterator_range_detail::iterator_range_base::operator[](boost::iterator_range_detail::iterator_range_base::difference_type) const [with IteratorT = boost::iterators::counting_iterator; boost::iterator_range_detail::iterator_range_base::reference = const int&; boost::iterator_range_detail::iterator_range_base::difference_type = long int]’:
test_counting_iterator_range_indexing.cpp:23:43: required from here
./boost/range/iterator_range_core.hpp:391:32: warning: returning reference to temporary [-Wreturn-local-addr]
return this->m_Begin[at];
^
```

The reason for the segmentation fault is that `iterator_range::operator[]` returns a reference to a stack-allocated object returned by `counting_iterator::operator[]`.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.