eng
eng

Reputation: 21

Using std::vector as a char buffer

I want to use std::vector as a char[] buffer. I did the following:

std::vector<char> buffer;
buffer.push_back('2');
buffer.push_back('5');
buffer.push_back('6');
std::cout << buffer.data() << "\n";
buffer.clear();
buffer.push_back('3');
std::cout << buffer.data() << "\n";

What I get:

256
356

What I want:

256
3

I am guessing that std::vector::clear() does not modify the underlying pointer.

Please suggest me a solution.

Upvotes: 1

Views: 2051

Answers (2)

john
john

Reputation: 87959

The idea is fine. The issue is not that clear isn't working, it's that you are printing the vector wrong.

buffer.data() returns a pointer to the data, a char* in other words. When you use std::cout on a char* it expects a nul terminated string (i.e. C style string), but you aren't giving it that as there is no nul character in your data, so you get unpredictable results.

Here's some code that prints the vector in the correct way (using std::copy and std::ostreambuf_iterator)

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    std::vector<char> buffer;
    buffer.push_back('2');
    buffer.push_back('5');
    buffer.push_back('6');
    std::copy(buffer.begin(), buffer.end(), std::ostreambuf_iterator(std::cout));
    std::cout << std::endl;
    buffer.clear();
    buffer.push_back('3');
    std::copy(buffer.begin(), buffer.end(), std::ostreambuf_iterator(std::cout));
    std::cout << std::endl;
    return 0;
}

Upvotes: 2

songyuanyao
songyuanyao

Reputation: 172924

Your code has undefined behavior; you should add the null terminator character '\0' at last (for the usage of std::vector<char> as c-style string literal). e.g.

std::vector<char> buffer;
buffer.push_back('2');
buffer.push_back('5');
buffer.push_back('6');
buffer.push_back('\0');
std::cout << buffer.data() << "\n";

buffer.clear();
buffer.push_back('3');
buffer.push_back('\0');
std::cout << buffer.data() << "\n";

Upvotes: 2

Related Questions