Skip to content

std::vector::operator[] allows out-of-bounds assignment on reserved elements in Clang/libc++ while at() correctly throws #153538

@hutuhutong

Description

@hutuhutong

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    hardeningIssues related to the hardening effortinvalidResolved as invalid, i.e. not a buglibc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions