Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check for invalidated iterator/dangling reference on heap reallocation #2183

Closed
dfrvfmst opened this issue Feb 29, 2024 · 2 comments
Closed
Assignees

Comments

@dfrvfmst
Copy link

Not sure if this is the right place for this issue.

As per std::vector on cppreference, iterators are potentially invalidated on certain operations:

  • push_back, emplace_back | If the vector changed capacity, all of them. If not, only end().

Demonstrate:

auto f()
{
    std::vector<int> v{1, 2, 3, 4};
    int &p = v.front();
    std::cout << std::format("int&: {}\n", p);
    v.push_back(5); // Triggers reallocation when changing capacity
    // p was potentially invalidated, using it can be use-after-free
    std::cout << std::format("int&: {}\n", p);
}

The above code snippet doesn't trigger any warning with clang-tidy. However, it's captured by AddressSanitizer:

==15550==ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000010 at pc 0x5636a3e859a5 bp 0x7ffd49ddf820 sp 0x7ffd49ddf810

C++ Core Guidelines should discourage the use of invalidated iterator and/or attempt to detect the use of dangling reference in compile-time.

@dfrvfmst
Copy link
Author

dfrvfmst commented Mar 3, 2024

I think it's covered in cplusplus/papers#312

@hsutter hsutter self-assigned this Apr 11, 2024
@hsutter
Copy link
Contributor

hsutter commented Apr 11, 2024

Editors call: We agree. This error is discouraged in ES.65 but that Guideline should explicitly mention that it applies to iterators as well (e.g., Note that by pointer here we mean any indirection to an object, such as an iterator or view). And this error is covered by the Lifetime profile (the live version of the doc in cplusplus/papers/#312 is this repo's Lifetime profile.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants