Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Effective Memory Management

Dynamic Strings

Strings present something of a quandary for programming language designers because they seem like a standard data type, but are not expressed in fixed sizes. Strings are so commonly used, however, that most programming languages need to have a built-in model of a string. In the C language, strings are somewhat of a hack, never given the first-class language feature attention that they deserve. C++ provides a far more flexible and useful representation of a string.

C-Style Strings

In the C language, strings are represented as an array of characters. The last character of a string is a null character (‘\0’) so that code operating on the string can determine where it ends. Even though C++ provides a better string abstraction, it is important to understand the C technique for strings because they still arise in C++ programming.

By far, the most common mistake that programmers make with C strings is that they forget to allocate space for the ‘\0’ character. For example, the string “hello” appears to be five characters long, but six characters worth of space are needed in memory to store the value, as shown in Figure 13-13.

Stack

Heap

myString 'h'

'e'

'l'

'l'

'o'

'\0'

Figure 13-13

C++ contains several functions from the C language that operate on strings. As a general rule of thumb, these functions do not handle memory allocation. For example, the strcpy() function takes two strings as parameters. It copies the second string onto the first, whether it fits or not. The following code attempts to build a wrapper around strcpy() that allocates the correct amount of memory and returns the result, instead of taking in an already allocated string. It uses the strlen() function to obtain the length of the string.

char* copyString(const char* inString)

{

char* result = new char[strlen(inString)]; // BUG! Off by one!

strcpy(result, inString);

return result;

}

365

Chapter 13

The copyString() function as written is incorrect. The strlen() function returns the length of the string, not the amount of memory needed to hold it. For the string “hello”, strlen() will return 5, not 6! The proper way to allocate memory for a string is to add one to the amount of space needed for the actual characters. It seems a little weird at first to have +1 all over, but it quickly becomes natural, and you (hopefully) miss it when it’s not there.

char* copyString(const char* inString)

{

char* result = new char[strlen(inString) + 1];

strcpy(result, inString);

return result;

}

One way to remember that strlen() only returns the number of actual characters in the string is to consider what would happen if you were allocating space for a string made up of several others. For example, if your function took in three strings and returned a string that was the concatenation of all three, how big would it be? To hold exactly enough space, it would be the length of all three strings, added together, plus one for the trailing ‘\0’ character. If strlen() included the ‘\0’ in the length of the string, the allocated memory would be too big. The following code uses the strcpy() and strcat() functions to perform this operation.

char* appendStrings(const char* inStr1, const char* inStr2, const char* inStr3)

{

char* result = new char[strlen(inStr1) + strlen(inStr2) + strlen(inStr3) + 1];

strcpy(result, inStr1);

strcat(result, inStr2); strcat(result, inStr3);

return result;

}

A complete list of C functions to operate on strings is found in the <cstring> header file.

String Literals

You’ve probably seen strings written in a C++ program with quotes around them. For example, the following code outputs the string hello by including the string itself, not a variable that contains it.

cout << “hello” << endl;

In the preceding line, “hello” is a string literal because it is written as a value, not a variable. Even though string literals don’t have associated variables, they are treated as const char*’s (arrays of constant characters).

String literals can be assigned to variables, but doing so can be risky. The actual memory associated with a string literal is in a read-only part of memory, which is why it is an array of constant characters. This

366

Effective Memory Management

allows the compiler to optimize memory usage by reusing references to equivalent string literals (that is, even if your program uses the string literal “hello” 500 times, the compiler can create just one instance of hello in memory). The compiler does not, however, force your program to assign a string literal only to a variable of type const char* or const char[]. You can assign a string to a char* without const, and the program will work fine unless you attempt to change the string. Generally, attempting to change the string will immediately crash your program, as demonstrated in the following code:

char* ptr = “hello”;

//

Assign

the string literal to a variable.

ptr[1] = ‘a’;

//

CRASH!

Attempts to write to read-only memory

 

 

 

 

A much safer way to code is to use a pointer to const characters when referring to string literals. The code below contains the same bug, but because it assigned the literal to a const character array, the compiler will catch the attempt to write to read-only memory.

const char* ptr = “hello”;

//

Assign the string literal

to a variable.

ptr[1] = ‘a’;

//

BUG! Attempts to write to

read-only memory

 

 

 

 

You can also use a string literal as an initial value for a stack-based character array. Because the stackbased variable cannot in any way refer to memory somewhere else, the compiler will take care of copying the string literal into the stack-based array memory.

char stackArray[] = “hello”; // Compiler takes care of copying the array and // creating appropriate size for stack array

stackArray[1] = ‘a’;

// The copy can be modified.

The C++ string Class

As we promised earlier, C++ provides a much-improved implementation of a string as part of the Standard Library. In C++, string is a class (actually an instantiation of the basic_string template class) that supports many of the same operations as the <cstring> functions but, best of all, takes care of memory allocation for you if you use it properly.

What Was Wrong with C-Style Strings?

Before jumping into the new world of the C++ string class, consider the advantages and disadvantages of C-style strings.

Advantages:

They are simple, making use of the underlying basic character type and array structure.

They are lightweight, taking up only the memory that they need if used properly.

They are low level, so you can easily manipulate and copy them as raw memory.

They are well understood by C programmers — why learn something new?

367

Chapter 13

Disadvantages:

They are unforgiving and susceptible to difficult memory bugs.

They don’t leverage the object-oriented nature of C++.

They come with a set of poorly named and sometimes confusing helper functions.

They require knowledge of their underlying representation on the part of the programmer.

The preceding lists were carefully constructed to make you think that perhaps there is a better way. As you’ll learn below, C++ strings solve all of these disadvantages of C strings and make the advantages moot.

Using the string Class

Even though string is a class, you can almost always treat it as though it were a built-in type, like int. In fact, the more you think of it as a simple type, the better off you are. Programmers generally encounter the least trouble with string when they forget that strings are objects.

Through the magic of operator overloading, C++ strings support concatenation with the + operator, assignment with the = operator, comparison with the == operator, and individual character access with the [] operator. These operators are what allow the programmer to treat string like a basic type. As the following code shows, you can perform these operations on a string without worrying about memory allocation.

int main(int argc, char** argv)

{

string myString = “hello”;

myString += “, there”;

string myOtherString = myString;

if (myString == myOtherString) { myOtherString[0] = ‘H’;

}

cout << myString << endl; cout << myOtherString << endl;

}

The output of this code is:

hello, there Hello, there

There are several things to note in this example. First, there are no memory leaks even though strings are allocated and resized left and right. All of these string objects were created as stack variables. While the string class certainly had a bunch of allocating and resizing to do, the objects themselves cleaned up this memory when they went out of scope.

368