Hello. I am a new member on this forum. I have been consulting it for a long time with great interest. Yesterday I found what I think is a bug with the Class String.

After creating a String initialized with an empty c string ( String * str = new String (""); ), the c_str () method returns a null pointer with my Teensy. I rather expect a valid pointer to an empty c string.

However if the initialization is done with a non-empty c string and then I reassign an empty c string after, c_str() returns a valid pointer to an empty c string.

The bug seems to have been introduced in the copy method in WString.cpp:

String & String::copy(const char *cstr, unsigned int length)
	if (length == 0) {
		if (buffer) buffer[0] = 0;
		len = 0;
		return *this;
	if (!reserve(length)) {
		if (buffer) {
			buffer = NULL;
		len = capacity = 0;
		return *this;
	len = length;
	strcpy(buffer, cstr);
	return *this;
With the addition of the condition if (length == 0) the buffer is never allocated with initialization of an empty c string.
I imagine the goal here was to avoid allocating a buffer if the String is empty. This is good for optimization but it introduced the bug for c_str().

To avoid this I propose to modify c_str() in WString.h so as to force the method to return a pointer to an dummy empty static c string if the buffer has never been allocated.
Like this:

static char dummy = 0;
const char * c_str() const {return (buffer == NULL) ? &dummy : buffer; }

With this simple modification in a future version the optimization remains and c_str() guarantees never return a null pointer.