What does vec.data() return if vec.size() == 0?

Viewed 2745

cppreference has this note for std::vector::data:

Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range, even if the container is empty.

What does "valid range" mean here exactly? What will data() return if the vector is zero-length?

Specifically, for a zero-length vector:

  1. Can data() ever be a null pointer?
  2. Can it be safely dereferenced? (Even if it points to junk.)
  3. Is it guaranteed to be different between two different (zero-length) vectors?

I am working with a C library that takes arrays and won't allow a null pointer even for a zero-length array. However, it does not actually dereference the array storage pointer if the array length is zero, it just checks whether it is NULL. I want to make sure that I can safely pass data() to this C library, so the only relevant question is (1) above. (2) and (3) are just out of curiosity in case a similar situation comes up.


Update

Based on comments that were not turned into answers, we can try the following program:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> v;
    cout << v.data() << endl;

    v.push_back(1);
    cout << v.data() << endl;

    v.pop_back();
    cout << v.data() << endl;

    v.shrink_to_fit();
    cout << v.data() << endl;

    return 0;
}

With my compiler it output:

0x0
0x7f896b403300
0x7f896b403300
0x0

This shows that:

  • data() can indeed be a null pointer, thus the answers are (1) yes (2) no (3) no

  • but it is not always a null pointer for a zero-size vector

Yes, obviously I should have tried this before asking.

3 Answers
Related