1

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.

2 Answers 2

2

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";
Sign up to request clarification or add additional context in comments.

1 Comment

Another way to output a char[] buffer without a null terminator is to use write() instead of <<, eg: std::cout.write(buffer.data(), buffer.size());
2

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;
}

1 Comment

std::copy()+std::ostreambuf_iterator is a bit overkill for this situation.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.