Chapter 21. Memory Access

Table of Contents

21.1. Pointer Pathology
21.2. Further Pointer Pathology with Heap Memory
21.3. Memory Access Summary
21.4. Introduction to Arrays
21.5. Pointer Arithmetic
21.6. Arrays, Functions, and Return Values
21.7. Different Kinds of Arrays
21.8. Valid Pointer Operations
21.9. Arrays and Memory: Important Points
21.10. Exercises: Memory Access
21.11. Review Questions

[ fromfile: memoryaccess.xml id: memoryaccess ]

Abstract

Arrays and pointers are low-level building blocks of C programs that provide fast access to hardware memory. This chapter discusses the different ways to organize and access memory.

Direct manipulation of memory entails some serious risks and requires good practices and thorough testing to avoid serious errors. Improper use of pointers and dynamic memory can cause program crashes that result from heap corruption and memory leaks. Heap corruption is especially difficult to debug because it generally leads to segmentation faults that halt the program at a point in the code that may be far from the point at which the heap became corrupted.

Both Qt and Standard Library container classes permit the safe use of dynamic memory without adversely affecting performance.[120] Arrays implement most container classes but are hidden from client code. The safety factors come from the careful design of each container API so that actions that might produce memory problems are not permitted.

Qt offers many containers, ranging from high-level template classes such as the ones discussed in Section 6.8, to low-level containers such as QBitArray and QByteArray.

Generally, when writing applications that reuse those containers, it is easy to avoid the use of arrays entirely. When Qt is not available, or when you need to write an interface to C code, you may need to use arrays and pointers and work directly with allocated memory.

Modern software often has colorful graphics and sound that require rapid processing for proper execution. That generally means that heavy use must be made of dynamic memory. Vast quantities of memory and secondary storage are available on the typical computing device – quantities that were unimaginable just a few years ago. But graphics, animation, and sound all require substantial amounts of memory that must be handled carefully and efficiently. That is why we focus on the proper management of memory resources and on the dire consequences of mismanagement.



[120] In the sequel, whenever we use the term container, with no further qualification, we mean Qt or Standard Library container.