ProAnswers.org

what is Stack,Static and Heap in C++

what is Stack,Static and Heap in C++

static variable (class)
lifetime = program runtime (1)
visibility = determined by access modifiers (private/protected/public)

static variable (global scope)
lifetime = program runtime (1)
visibility = the compilation unit it is instantiated in (2)

heap variable
lifetime = defined by you (new to delete)
visibility = defined by you (whatever you assign the pointer to)

stack variable
visibility = from declaration until scope is exited
lifetime = from declaration until declaring scope is exited

The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.

[b]Static [/b]data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope. These static members have external linkage.



The [b]heap[/b] is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.



http://www.timestravel.co/flights/Jamaica/