In this post, we will see how to resolve Interfacing with C library, why does this not work (strcpy, std::string, char *)?
Question:
I am writing a program that needs to interface with an external C library. I have to pass a char* parameter to a function, to get a name of a data set. Essentially the situation look like belowa
does not contain "test"
in my example and instead is empty:-std=c++11
.I even looked in the inside of the “give_name” function with gdb (in the real library and not a simple example above), and there the variable corresponding to
name
contains proper text.I feel like I am missing something important, any help? Even funnier that this works in different place of the code? Is this the mythical undefined behaviour?
Best Answer:
While you reserved storage ina
to give it a capacity of 10, its size is still zero. You are not supposed to modify the string buffer like this.The stream output for
std::string
will write the characters up to its known end of string, not the NUL-terminator if you happened to break the rules. So you might see your “expected” result if you do:In general it’s not recommended to write NUL-terminated strings directly into a
std::string
buffer. But if you do, you should calculate the new length and resize
the string accordingly.If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com