• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Interfacing with C library, why does this not work (strcpy, std::string, char *)?

Resolved: Interfacing with C library, why does this not work (strcpy, std::string, char *)?

0
By Isaac Tonny on 15/03/2023 Issue
Share
Facebook Twitter LinkedIn

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 below
Now, I am stumped, why a does not contain "test" in my example and instead is empty:
The above was compiled with gcc12.2 with -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 in a 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:
But that is a super bad idea. You have already broken the string, and it cannot fulfill its behavioral guarantees as per the standard.
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

c++ c++11
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to set consistent decimal separators in R data frame?

26/03/2023

Resolved: How to resolve LNK2001 in c++ projects

26/03/2023

Resolved: How to correctly initialize vector of number in Typescript

26/03/2023

Comments are closed.

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.