1

I need to use an old-style c-function that needs an output buffer. Instead of using a char-array for this and afterwards copy from this char-array to the std::string, I want to avoid the extra copy operation and use a preallocated str::string object as buffer:

https://godbolt.org/z/jx85off3G

#include <string>
#include <cstring>
#include <iostream>

#define FF_MAX_LFN 255

void old_c_filler(char* s, int l) {
    strncpy(s, "abc", l);
}

int main() {
  std::string s(FF_MAX_LFN + 1, '\0');
  old_c_filler(s.data(), FF_MAX_LFN);
  s.resize(strnlen(s.c_str(), FF_MAX_LFN));
  s.shrink_to_fit();

  std::cout << s << '\n';
}

Is it save to do so? Especially, is it save to resize this way? (The resize is needed because the string size must represent the real size of the c-string).

wimalopaan
  • 4,838
  • 1
  • 21
  • 39

0 Answers0