3

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).

4
  • Your code still contains a lot of copying and memory re-allocation, I usually do it like this, live demo : onlinegdb.com/ywY55t8C3 Commented Jan 6, 2022 at 5:26
  • You does the copying twice: 1) in c-function 2) in ctor of string. So worse than mine. Commented Jan 6, 2022 at 5:38
  • And this does not answer the questions. Commented Jan 6, 2022 at 5:38
  • I stand corrected ;) And there is a duplicate here : stackoverflow.com/questions/58718816/… Commented Jan 6, 2022 at 7:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.