C ++: is it safe to move jpeg in memory using std :: string?

I have an external_jpeg_func() that takes jpeg data in a char array to do something with it. I can not change this function. To provide a char array, I am doing something like the following:

 //what the funcs take as inputs std::string my_get_jpeg(); void external_jpeg_func(const char* buf, unsigned int size); int main () { std::string myString = my_get_jpeg(); external_jpeg_func(myString.data(), myString.length() ); } 

My question is: is it safe to use a string to wrap a char array? Can jpeg (or possibly some binary file format) collide with characters like "\ 0" and cause data loss?

+4
source share
3 answers

My recommendation would be to use std::vector<char> rather than std::string , in this case; The danger with std::string is that it provides the c_str() function, and most developers believe that the contents of std::string completed with NUL, although std::string provides a size() function that can return a different value, than what you get by staying at NUL. However, while you try to always use a constructor that takes a size parameter, and you try not to pass .c_str() to anything, there is no problem using a string here.

Although there is no technical advantage to using std::vector<char> compared to std::string , I feel that it handles other developers better so that the content is interpreted as an arbitrary sequence of bytes, rather than NUL-complete text content. Therefore, I would choose the first for this additional readability. However, I have worked with a lot of code that uses std::string to store arbitrary bytes. In fact, the C ++ proton compiler generates such code (although, I should add that I do not think that it was a good choice for readability of the reasons I spoke about).

+10
source

std::string does not specifically handle null characters unless you give it an explicit string length. This way your code will work fine.

Although, in C ++ 03, strings are not technically required for storage in continuous memory. Almost every std::string implementation that you find will actually save them that way, but this is not technically necessary. C ++ 11 fixes this.

So, I suggest you use std::vector<char> in this case. std::string will not buy you anything over std::vector<char> , and it’s more explicit that it is an array of characters and not a possible printable string.

+6
source

I think it is better to use char char [] or std :: vector <char> array. This is the standard way to store images. Of course, a binary can contain 0 characters.

+2
source

All Articles