Question: If not from the heap, where does the memory for C come from?
From the stack (or in the case of a global variable or function ‘static’ variable, from a statically allocated region that exists independently of both the heap and the stack).
Strictly speaking, C++ has no concept of heap or stack (other than as data structures in the standard library, which are fundamentally different to “the” heap and stack that are the prevalent mechanisms used for allocation of memory by running programs); the exact mechanism for allocation and management of memory is not specified. In practice, there are two ways for a program to allocate memory at run time on most systems: from the heap (which is itself built on memory chunks obtained from the operating system), or from the stack (the same stack that is used to store the return address and save temporary values when functions are called).
Memory for the stack is usually allocated when (or just before) the program begins execution, and it usually needs to be contiguous. Memory for the heap is usually obtained dynamically and does not normally need to be contiguous (though in practice heap memory is often allocated in contiguous chunks).
Note that your first example:
ClassName* p;
p = new ClassName;
… actually embodies two allocations: one for the ClassName
object (dynamic storage, allocated on the heap) and one for the pointer variable p
(automatic storage, allocated on the heap).
In practice, local variables will not always require stack allocation – their values can sometimes be kept in registers (or in some cases, the storage can be optimised away altogether, especially if the value is unused or is a compile-time constant). And theoretically, heap allocations can also potentially be optimised away.
8
solved Where does the memory come from to initialize a C++ object without the new keyword?