This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: char* to string: Differences between v4.4.5 and v4.6.1


Resendin to the mailing list as plain text.

On 21/03/13 17:46, Ángel González wrote:
> On 21/03/13 17:08, Alexander Striffeler wrote:
>> Hello
>>
>> I'm using g++ for a project where I have to store serialized data as
>> a char*. Of course, these serialized bits are likely to contain NULL
>> characters which implies that NULL-terminating strings obviously are
>> a bad choice. Unfortunately, storing the information as char* is
>> predetermined. This means I serialize the objects, process them as
>> std::string and then store them as char*. When I try to recover the
>> std::string, the behaviour is kind of strange (consider the code
>> snippet below as an example):
>>
>>         const char* hello = "hel\0lo";
>>         std::string s(hello, 6);
>>         std::cout << "s.length() = " << s.length() << '\n';
>>         std::cout << "s = \"" << s << "\"\n";
>>
>> prints 'hel' on my machine running g++ v4.6.1 (which apt pretends to
>> be up to date) while it prints 'hello' on a stackoverflow
>> contributor's machine running version 4.4.5. (For the full question
>> see stackoverflow.com/questions/15525208).
>>
>> Is this a known issue - and does anyone know a workaround?
>>
>> Any hints are very appreciated - TIA!
>>
>> Cheers
>> Alex
>>
> [1] defines the constructor you are using «string (const char* s,
> size_t n);» as
> «Copies the first /n/ characters from the array of characters pointed
> by /s/.», which is exactly what you want (ie. it doesn't stop at a
> \0). Looking at the standard [2] confirms it, see page 634 of [3]:
> «basic_string(const charT* s, size_type n, const Allocator& a =
> Allocator());
> 7 Requires: s shall not be a null pointer and n < npos.
> 8 Effects: Constructs an object of class basic_string and determines
> its initial string value from the
>  array of charT of length n whose first element is designated by s, as
> indicated in Table 66.»
>
> Testing with g++ 4.7.2, I see "hello". What you haven't provided is
> the output of s.length() on your machine. If it's 6 I would expect the
> problem be in std::cout or its underlying calls, not in std::string.
>
> Regards
>
> 1- http://www.cplusplus.com/reference/string/string/string/
> 2- http://www.open-std.org/JTC1/SC22/WG21/
> 3- http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2011/n3242.pdf


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]