Home > Net >  How to correctly use vector<uint8_t>.data()?
How to correctly use vector<uint8_t>.data()?

Time:12-28

vector.data() should return a pointer to the first element, but when I use it on a vector<uint8_t>, it somhow returns somthing else:

int main() {
    std::string myString = {"a b c all the way long"};
    std::vector<uint8_t> myVec(myString.begin(), myString.end());
    std::cout << myVec.data() << std::endl;
    
    std::vector<int> anotherVec = {4,5,2,3}; 
    std::cout<< anotherVec.data() << std::endl;

    return 0; 
}

program prints:

a b c all the way long
0x124bf00

Why does the first print show all of the vector, and the second print shows the pointer? I was expecting both to print a pointer.

The real issue is that on another big program, when I print vector<uint8_t>.data() with cout, it prints garbage after it (when I look at it in the debugger, I don't see the garbage).

CodePudding user response:

The data() function returns a pointer to the first element.

myString is a vector of uint8_t values, so data() will return a value of type uint8_t*. uint8_t is a type based on char, so the << stream output operator will treat it as a null-terminated string. The problem here is that myVec doesn't contain a null-terminated string, so this is technically undefined behavior.

For anotherVec, that's a vector of int values, which means that data() returns a value of type int*, which has no specific overload for the << stream output operator. Instead, it uses the closest possible overload, which is the one to print generic pointers of type void*.

If you want the first to print the pointer itself, then you need to explicitly cast the pointer to void*:

std::cout << static_cast<void*>(myVec.data()) << '\n';
  • Related