Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 3 TYPES, STORAGE, AND VARIABLES

The Stack and the Heap

While a program is running, its data must be stored in memory. How much memory is required for an item, and where and how it’s stored, depends on its type.

A running program uses two regions of memory to store data: the stack and the heap.

The Stack

The system takes care of all stack manipulation. You, as the programmer, don’t need to do anything with it explicitly. But understanding its basic functions will give you a better understanding of what your program is doing when it’s running and allow you to better understand the C# documentation and literature.

The stack is an array of memory that acts as a last-in, first-out (LIFO) data structure. It stores several types of data:

The values of certain types of variables

The program’s current execution environment

Parameters passed to methods

Facts About Stacks

The general characteristics of stacks are the following:

Data can be added to and deleted only from the top of the stack.

Placing a data item at the top of the stack is called pushing the item onto the stack.

Deleting an item from the top of the stack is called popping the item from the stack.

Figure 3-6 illustrates the functions and terminology of the stack.

Figure 3-6. Pushing and popping on the stack

39

CHAPTER 3 TYPES, STORAGE, AND VARIABLES

The Heap

The heap is an area where chunks of memory are allocated to store certain kinds of data objects. Unlike the stack, memory can be stored and removed from the heap in any order. Figure 3-7 shows a program that has stored four items in the heap.

Figure 3-7. The memory heap

Although your program can store items in the heap, it cannot explicitly delete them. Instead, the CLR’s garbage collector (GC) automatically cleans up orphaned heap objects when it determines that your code is no longer accessing them. This frees you from what in other programming languages can be an error-prone task. Figure 3-8 illustrates the garbage collection process.

Figure 3-8. Automatic garbage collection in the heap

40

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]