0

I think I didn't understand the initialization of std::vector.

The code below seems to compile and run fine with gcc, clang, and MSVC.

#include <iostream>
#include <vector>
int main() {
    std::vector<int> v{{}};

    v[10] = 11; // if initialize with v{}, segmentation fault.

    std::cout << "v[10]:" << v[10] << std::endl; // prints v[10]:11
    
    for (auto e : v) // prints only v[x]:0
        std::cout << "v[x]:" << e << std::endl;    
}

// result:
// v[10]:11
// v[x]:0

Is accessing the element with v[10] causing an undefined behavior?

Why does the above code with v{{}} run fine, but not with v{}?

Edit) Originally I didn't use the correct terminology, my fault. When I said 'not compiled', I was trying to say 'not run(after compile)'.

starriet
  • 2,565
  • 22
  • 23
  • 2
    Your title seems off. It's not the initialization of the vector that causes undefined behavior, but the out-of-bounds access. The initialization merely changes how that undefined behavior manifests. – JaMiT Mar 26 '23 at 06:03
  • [Not reproducible](https://godbolt.org/z/GEY95aYhz). – n. m. could be an AI Mar 26 '23 at 06:11
  • What happened to me... Sorry I was trying to say 'not run', not 'not compile'. @bolov Thanks for pointing that out. – starriet Mar 26 '23 at 06:15

1 Answers1

5
std::vector<int> v{};

This initializes v as a vector of size 0. Attempting to access any element in it results in Undefined Behavior. v[10] is out of bounds and UB.

std::vector<int> v{{}};

This initializes v as a vector with a single element. That single element is initialized with {} i.e. int{} i.e. 0. Attempting to access any element except v[0] results in UB. v[10] causes UB.

bolov
  • 72,283
  • 15
  • 145
  • 224