7

How can I access the contiguous memory buffer used within a std::vector so I can perform direct memory operations on it (e.g. memcpy)? Also, it is safe to perform operations like memcpy on that buffer?

I've read that the standard guarantees that a vector uses a contiguous memory buffer internally, but that it is not necessarily implemented as a dynamic array. I figure given that it is definitely contiguous, I should be able to use it as such - but I wasn't sure if the vector implementation stored book-keeping data as part of that buffer. If it did, then something like memcpying the vector buffer would destroy its internal state.

3

7 Answers 7

16

In practice, virtually all compilers implement vector as an array under the hood. You can get a pointer to this array by doing &somevector[0]. If the contents of the vector are POD ('plain-old-data') types, doing memcpy should be safe - however if they're C++ classes with complex initialization logic, you'd be safer using std::copy.

1
  • The standard guarantees the vector to be a contiguous block.
    – GlGuru
    Dec 7, 2017 at 23:20
10

Simply do

&vec[0];

// or Goz's suggestion:
&vec.front();

// or
&*vec.begin();
// but I don't know why you'd want to do that

This returns the address of the first element in the vector (assuming vec has more than 0 elements), which is the address of the array it uses. vector storage is guaranteed by the standard to be contiguous, so this is a safe way to use a vector with functions that expect arrays.

Be aware that if you add, or remove elements from the vector, or [potentially] modify the vector in any way (such as calling reserve), this pointer could become invalid and point to a deallocated area of memory.

3
  • 2
    Or &vec.front() which is much much nicer than your begin method above ;)
    – Goz
    Aug 30, 2011 at 21:12
  • 2
    Nps :) I tend to prefer using it to using &vec[0] as it makes it far far more obvious that I'm using a vector :)
    – Goz
    Aug 30, 2011 at 21:20
  • why not vec.data()?
    – Ocelot
    May 29, 2020 at 1:55
6

You can simply do:

  &vect[0]

The memory is guaranteed contiguous so its safe to work with it with C library functions such as memcpy. However, you shouldn't persist pointers into the contiguous data because vector resizes may reallocate and copy the memory to a different location. IE the following would be bad:

  std::vector<char> charVect;
  // insert a bunch of stuff into charVect
  ...
  char* bufferPtr = &charVect[0];
  charVect.push_back('a'); // potential resize
  // Now bufferPtr may not be valid since the resize may have moved
  // the vectors contents
  bufferPtr[0] = 'f'; // **CRASH**
2
&myvec[0]

But note that using memcpy is really only applicable if this is a vector of PODs or primitive types. Doing direct memory manipulation of anything else leads to undefined behaviour.

2

The simplest way is to use &v[0], where v is your vector. An example:

int write_vector(int fd, const std::vector<char>& v) {
   int rval = write(fd, &v[0], v.size());
   return rval;
}
1

Yes - since the standard guarantees contiguous placement of the vector's internal data, you can access a pointer to the first element in the vector via:

std::vector<int> my_vector;
// initialize...

int* arr = &my_vector[0];
0

While you can safely read the right amount of data from the underlying storage, writing there may not happen to be a good idea, depending on the design.

    vlad:Code ⧴ cat vectortest.cpp
    #include <vector>
    #include <iostream>
    int main()
    {
        using namespace std;
        vector<char> v(2);
        v.reserve(10);
        char c[6]={ 'H', 'e', 'l', 'l', 'o', '\0' };
        cout << "Original size is " << v.size();
        memcpy( v.data(), c, 6);
        cout << ", after memcpy it is " << v.size();
        copy(c, c+6, v.begin());
        cout << ", and after copy it is " << v.size() << endl;
        cout << "Arr: " << c << endl;
        cout << "Vec: ";
        for (auto i = v.begin(); i!=v.end(); ++i) cout << *i;
        cout << endl;
    }
    vlad:Code ⧴ make vectortest
    make: `vectortest' is up to date.
    vlad:Code ⧴ ./vectortest
    Original size is 2, after memcpy it is 2, and after copy it is 2
    Arr: Hello
    Vec: He
    vlad:Code ⧴

So if you are writing past the size(), then the new data is not accessible by class methods.

You can account for that and ensure the size is enough (e.g. vector<char> v(10)), but do you really want to make software where you are fighting the standard library?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.