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

Chapter 13

Accessing Out-of-Bounds Memory

Earlier in this chapter, you read that since a pointer is just a memory address, it is possible to have a pointer that points to a random location in memory. Such a condition is quite easy to fall into. For example, consider a C-style string that has somehow lost its ‘\0’ termination character. The following function, which attempts to fill the string with all ‘m’ characters, would instead continue to fill the contents of memory following the string with ‘m’s.

void fillWithM(char* inStr)

{

int i = 0;

while (inStr[i] != ‘\0’) { inStr[i] = ‘m’;

i++;

}

}

If an improperly terminated string were handed to this function, it would only be a matter of time before an essential part of memory was overwritten and the program crashed. Consider what might happen if the memory associated with the objects in your program is suddenly overwritten with ‘m’s. It’s not pretty!

Bugs that result in writing to memory past the end of an array are often called buffer overflow errors. Such bugs have been exploited by several high-profile viruses and worms. A devious hacker can take advantage of the ability to overwrite portions of memory to inject code into a running program.

Luckily, many memory checking tools detect buffer overflows as well. Also, using higher-level constructs like C++ strings and vectors will help prevent numerous bugs associated with writing to C-style strings and arrays.

Summar y

In this chapter, you learned the ins and outs of dynamic memory, from the basic syntax to the low-level underpinnings. Aside from memory checking tools and careful coding, there are two keys to avoiding dynamic memory-related problems. First, you need to understand how pointers work under the hood. In reading about two different mental models for pointers, we hope you are confident that you know how the compiler doles out memory. Second, you can avoid all sorts of dynamic memory issues by obscuring pointers with stack-based objects, like the C++ string class and smart pointers.

378