Writing to index of vector beyond end of container

后端 未结 2 587
夕颜
夕颜 2021-01-29 16:14

Why does the following work? I thought that writing to an an index of a vector object beyond the end of the vector object would cause a segmentation fault.

#incl         


        
相关标签:
2条回答
  • 2021-01-29 16:35

    So under the covers what actually happens when you try to address an element of an array or vector that is outside the container's bounds is a memory dereference to a piece of memory that is not part of the container. However, reads and writes to this location can "work" or appear to work because it is just more memory that you are reading/writing to. You are doing something very very bad. You will generally see random junk when accessing memory outside of your bounds because it can belong to something else or is leftovers from a previous process because the memory controller will not naturally zero out memory on its own. So the best practice is to use the size of the container to check your reads and writes if you are ever in doubt as to if you are outside the bounds of the container. You can use vector.size() to find the current size of the container.

    0 讨论(0)
  • 2021-01-29 16:58

    Somebody implementing std::vector might easily decide to give it a minimum size of 10 or 20 elements or so, on the theory that the memory manager likely has a large enough minimum allocation size that it will use (about) the same amount of memory anyway.

    As far as avoiding reading/writing past the end, one possibility is to avoid using indexing whenever possible, and using .at() to do indexing when you truly can't avoid it.

    I find that I can usually avoid doing indexing at all by using range-based for loops and/or standard algorithms for most tasks. For a trivial example, consider something like this:

    int main() {
        vector<int> x(1);
        x.push_back(1);
    
        for (auto i : x)
            cout << i << "\n";
    }
    

    .at() does work, but I rarely find it useful or necessary--I suspect I use it less than once a year on average.

    0 讨论(0)
提交回复
热议问题