Home > OS >  std::vector, char *, and C API
std::vector, char *, and C API

Time:03-07

I want to use some C API that requires a buffer of char, I'm thinking of using std::vector as the backer buffer. What I have in my mind for now is

  • obtain the size required by the C API
  • create a vector and reserve its size accordingly
  • feed the vector to the C API
  • get the number of bytes written by the C API
  • resize the vector accordingly

The following code outlines the idea:

int main(){
  auto required_size = get_required_buffer_size();

  auto buffer = std::vector<char>{};
  buffer.resize(required_size);

  auto read_size = read_data(std::data(buffer), buffer.capacity());
  buffer.resize(read_size);
}

Is this a correct usage of std::vector, or am I shooting myself in the foot somewhere?

Edit: Change reserve to resize since the last resize will overwrite data written by read_data

CodePudding user response:

What you have is very close, but it could use some subtle changes:

auto buffer = std::vector<char>{};
buffer.resize(required_size);

can be reduced to

std::vector<char> buffer(required_size);

And buffer.capacity() needs to be either required_size or buffer.size().

int main(){
  auto required_size = get_required_buffer_size();

  std::vector<char> buffer(required_size);

  auto read_size = read_data(buffer.data(), buffer.size());
  buffer.resize(read_size);
}

That being said, in cases where char[] buffers are needed, I prefer to use std::string instead:

int main(){
  auto required_size = get_required_buffer_size();

  std::string buffer(required_size, '\0');

  auto read_size = read_data(buffer.data()/*or: &buffer[0]*/, buffer.size());
  buffer.resize(read_size);
}
  • Related