Game Engine Architecture

(Ben Green) #1
119

U32* getMeaningOfLife()
{
U32 anInteger = 42;
return &anInteger;
}

You might get away with this if you use the returned pointer immediately and
don’t call any other functions in the interim. But more oft en than not, this kind
of code will crash—in ways that can be diffi cult to debug.


3.2.3.3. Dynamic Allocation Heap


Thus far, we’ve seen that a program’s data can be stored as global or static
variables or as local variables. The globals and statics are allocated within the
executable image, as defi ned by the data and BSS segments of the executable
fi le. The locals are allocated on the program stack. Both of these kinds of stor-
age are statically defi ned, meaning that the size and layout of the memory
is known when the program is compiled and linked. However, a program’s
memory requirements are oft en not fully known at compile time. A program
usually needs to allocate additional memory dynamically.
To allow for dynamic allocation, the operating system maintains a block
of memory that can be allocated by a running program by calling malloc()
and later returned to the pool for use by other programs by calling free().
This memory block is known as heap memory, or the free store. When we al-
locate memory dynamically, we sometimes say that this memory resides on
the heap.
In C++, the global new and delete operators are used to allocate and free
memory to and from the heap. Be wary, however—individual classes may
overload these operators to allocate memory in custom ways, and even the
global new and delete operators can be overloaded, so you cannot simply as-
sume that new is always allocating from the heap.
We will discuss dynamic memory allocation in more depth in Chap-
ter 6. For additional information, see htt p://en.wikipedia.org/wiki/Dynamic_
memory_allocation.


3.2.4. Member Variables


C structs and C++ classes allow variables to be grouped into logical units.
It’s important to remember that a class or struct declaration allocates no
memory. It is merely a description of the layout of the data—a cookie cutt er
which can be used to stamp out instances of that struct or class later on.
For example:


3.2. Data, Code, and Memory in C/C++

Free download pdf