<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/153538>153538</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            std::vector::operator[] allows out-of-bounds assignment on reserved elements in Clang/libc++ while at() correctly throws
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            clang,
            libc++
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          hutuhutong
      </td>
    </tr>
</table>

<pre>
    I am not sure whether this behavior  needs adjustment. Assigning to a std::vector element via operator[] at an index beyond the current size but within the reserved capacity does not trigger a runtime error in Clang/libc++. In contrast, using v.at() for the same index correctly throws a std::out_of_range exception.

clang20.1.0   -O0 -std=c++20  -stdlib=libc++ 
========= code  ========
#include <vector>
#include <iostream>

int main() {
    std::vector<int> v;
    v.reserve(10); 
    // v.at(3) = 42; // will trigger the error
    v[3] = 0;   // not trigger the error
 std::cout << v[3] << "\n";
}

========= output  ========
when v.at(3) = 42 is executed, the program output;
ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 139
libc++abi: terminating due to uncaught exception of type std::out_of_range: vector
Program terminated with signal: SIGSEGV

when  v[3] = 0  is executed, the program output;
ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 0
0
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJzMVcFu4zgM_RrlQsRQpHgSH3xwk3bQw2IXKLDXgSyztgayFEhU0u7XL6QkTbfTznmBAEZE8onkI59UjGZ0iC2r71i9X6hEkw_tlChNibwbF70fXttHUDM4TxBTQDhNSBMGoMlE6HFSR-MDgEMcIqjhZ4o0o6MKuoJu3AjkQUGkgcmOye6ImnwAtJj94GgU-AMGRT6c8wBFoBwYN-AL9Pjq3QA0IegUQo6I5h-EPhGcDE3GFVvAiOGIA2h1UNrQKwweY8maghlHDKAgJEdmRsAQfADjYGeVG5l4sKbXTNwxcV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