Understanding Program Memory

The chapter starts by looking at how the system stores (in the computer's memory) the data used by an application. Having a clear understanding of memory layout makes it easier to get started with pointers.

The point of any computer program is to process data. This data is stored in your computer's main memory. Every piece of data in memory has a unique address, defined in bytes. Some of the pieces have a name in addition to an address; those pieces are called variables, which is what you have been using so far.

Picture your computer's memory as a very long row of cells that store data, each with a unique address, and each 1 byte in size. The system assigns your variables to these memory cells, and every variable gets a unique address.

Different variable types take up a different quantity of cells. Integers take up 4 bytes of space and the chars use only 1 byte each. Floats and doubles will use different amounts of memory too.

Alignment

In Figure 9.1, you can also see that there's a memory gap between variables d and e. This occurs because an integer's starting addresses has to be a multiple of four. So e must be addressed beginning at 16, not 14.

Figure 9.1. One possible memory layout for five different variables.


It's said that variable types are aligned on their natural boundaries (like integers start on multiples of four). You don't have to worry about alignment yourself; the C compiler will correctly arrange alignment of all variables automatically.

Like a variable's size, the alignment is system-dependent and it may vary on your system.


To illustrate this, let's look at how C might lay out in memory the variables in the following definitions:

int  a = -40;
int  b = 7853;
char c = 74;
char d = 19;
int  e = 449378;

Figure 9.1 shows how these five variables might be stored in memory. The actual addresses are system-dependent; this is just one possible example of how the data might be arranged.

So far this book hasn't used data without giving it a name. That concept will be approached in the next chapter. In this chapter you'll see how to access variables (data with names) using their addresses instead of their names, and you'll also find out why this is useful in real programs.

The first thing you need to know, of course, is how to get the address of a variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset