[Dev] null terms for strings
Tanner Lovelace
dev@trilug.org
07 May 2002 14:55:32 -0400
On Tue, 2002-05-07 at 14:30, M. Mueller wrote:
> Here's a little program that captures a problem I had today. I have a map
> container, map<string, t_myStruc), that I want to duplicate on another
> machine. I pack each entry into datagram and send it via sockets to another
> machine where each packet is collected and used to build a copy of the map
> entry by entry. So, I convert the string key to an array of chars for the
> journey to the other side. In the process I got confused about the function
> of null terminators on char array strings versus string objects.
>
Well, for one thing, a C++ string may or may not be null terminated.
Officially, it's not specified as to how they are stored internally.
So, when in doubt, assume it's not.
> To compile: g++ -o test test.cpp
>
> <snip start>
> #include <string>
> using namespace std;
>
> main()
> {
> string a;
> a = 'a';
> a += ' ';
> a += 's';
> a += 't';
> a += 'r';
> a += 'i';
> a += 'n';
> a += 'g';
> a += '\0';
> string b;
> b = 'a';
> b += ' ';
> b += 's';
> b += 't';
> b += 'r';
> b += 'i';
> b += 'n';
> b += 'g';
>
> if (a == b)
> cout << "a equals b\n";
> else
> cout << "a not equals b\n";
>
> if (strcmp(a.c_str(), b.c_str()) == 0)
> cout << "a.c_str() equals b.c_str()\n";
> else
> cout << "a.c_str() not equals b.c_str()\n";
>
> }
> <snip end>
Well, I haven't run it, but just looking at it, I'd say the
strings are not the same. String a has a null character at
the end and string b doesn't.
In addition, I'd be interested in seeing what the .c_str()
function returned. I'd bet it doesn't do any checking for
stuff like this and the c-style strings that get returned
*are* the same (because they *must* have a null at the end)
even though the C++ strings are not.
I would just suggest sending over the output of the .c_str()
function of each string and then using the string constructor
to recreate them on the other side.
Tanner
--
Tanner Lovelace | lovelace@wayfarer.org | http://wtl.wayfarer.org/
--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--
GPG Fingerprint = A66C 8660 924F 5F8C 71DA BDD0 CE09 4F8E DE76 39D4
GPG Key can be found at http://wtl.wayfarer.org/lovelace.gpg.asc
--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--
Have we sent the "Don't shoot, we're pathetic" transmission yet?
Commander John Crichton (Farscape)