Mikhail Tal
Mikhail Tal

Reputation: 13

what exactly do stack and mean in context of memory allocation

I read things like "memory is allocated in a stack " or things like "these variable are placed in a heap ". I had once studied a book on microprocessor and can faintly remember that there had been topics or sections on something called as stack . And I do know that stacks also mean a kind of LIFO type data structure .

So , I feel confused as to what stacks imply . Are there memory locations in a every microprocessor other than the registers which are called as stack ?

Upvotes: 0

Views: 225

Answers (1)

geza
geza

Reputation: 30010

I'll describe the most common situation.

In this context, stack is a dedicated memory for a program (more precisely, for a thread). This memory is allocated automatically by the operating system, when your program is started. Usually (but not always), stack is allocated from the main memory (so it is not a special memory in the CPU).

It's name is stack, because it is used "LIFO style". When a function is called, its local variables gets allocated from the stack ("pushed to the stack"). When it returns, these variables are freed ("pop from the stack").

About heap: heap is the place from where one can allocate memory in a more flexible manner than stack. Heap storage space is usually much larger than the stack. And the allocated space will be available even after the function (which allocated the space) returns. And for languages which doesn't have garbage collection, you have to manually free the allocated space. This heap is not to be confused with the data structure heap, which is a completely different thing.

char *var;
void example(int length) {
  char stackVar[1024]; // a 1024 element char array allocated on the stack
  char *heapVar = new char[length]; // a length sized variable allocated on the heap, and a pointer (heapVar) to this place allocated on the stack

  var = heapVar; // store a pointer to the allocated space

  // upon return, stackVar is automatically freed
  //              the pointer heapVar automatically freed
  //              the space that heapVar points to is not freed automatically, can be used afterwards (via the var pointer)
}

Upvotes: 1

Related Questions