Home > Software engineering >  Is std::vector.data() null terminated on a vector of pointers?
Is std::vector.data() null terminated on a vector of pointers?

Time:03-03

I am using a C library in my C application. One of the functions needs a null terminated array of pointers.

Since I am using C , I am storing the elements of the array in a std::vector.

I would like to know if it's safe to simply call data() on my vector and pass the result to the library function.

Exemple :

std::vector<struct A *> vec;

//library_function(struct A **array);
library_function(vec.data());

Of course, if I change the elements in the vector then the pointer returned by data() will be invalidated, but that is not an issue here (I can call the function again when updating the vector).

I am just affraid this might be undefined behavior, since I can't see anywhere mentioned that data() is termined by a null pointer and not by random garbage.

The standard does say :

const T* data() const noexcept;

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

So there is a terminating element, but it doesn't say if that element is initialized, and if it is, with what value.

Is it specified somewhere else that I missed ?
Or do I have to allocate a raw array and null terminate it myself ?

CodePudding user response:

A vector of pointers is null terminated if the last element of the vector is null. There is no extra null element after the last element (like there would be a null terminator character after the last element of a std::string). The last element of a vector isn't null automatically. If you need the last element to be null, then you must insert the null element.

Example:

std::vector<A>  vec_of_struct(size);
std::vector<A*> vec_of_ptrs;
vec_of_ptrs.reserve(size   1);
std::ranges::copy(
    std::views::transform(
        vec_of_struct,
        [](A& a) { return &a; }
    ),
    std::back_inserter(vec_of_ptrs)
);
vec_of_ptrs.push_back(nullptr); // null terminator pointer
library_function(vec_of_ptrs.data()); // C function
  • Related