-3

My question here is What is stack and heap memory Why we need both of these memories what are the pros and cons of each

7
  • 3
    Try to answer something easier, like "What is Google?", then try "How do I use Google?". After learning how to search, come back and try it here on StackOverflow, and you might notice that this question has probably been ask 400 gazillion times. Commented Jan 21, 2011 at 10:02
  • 2
    Surely that's in the lecture notes Commented Jan 21, 2011 at 10:02
  • 2
  • I pressurized here on the "WHY" thing Commented Jan 21, 2011 at 11:53
  • The answer to "why" is that they do different things. To understand that you need to understand what they do. Refer to your lecture notes, other linked questions, Wikipedia (probably) and so on. Commented May 15, 2012 at 16:27

3 Answers 3

2

In a nutshell:

The stack - The memory the program uses to actually run the program. This contains local variables, call-back data (for example when you call a function, the stack stores the state and place you were in the code before you entered the new function), and some other little things of that nature. You usually don't control the stack directly, the variables and data are destroyed, created when you move in and out function scopes.

The heap - The "dynamic" memory of the program. Each time you create a new object or variable dynamically, it is stored on the heap. This memory is controlled by the programmer directly, you are supposed to take care of the creation AND deletion of the objects there.

Sign up to request clarification or add additional context in comments.

Comments

1

In C / C++ language memory allocated onto the stack is automatically free when the allocating scope ends, memory on the heap has to be free with some policy ( free(), delete ... or some garbage collector ). Memory allocated on the heap is visible among different function scope. In the stack we can't allocate big chunk of memory so heap is also useful when tou need to allocate big space for data.

1 Comment

In "C/C++" you don't even have to have a heap (or stack, other than std::stack) to be a conforming implementation.
0

I am not sure in which context you are asking but i can answer from their use in memory allocation. Both these data structures are required my platforms like .NET for Garbage collection. Remember all value types are stored on stack and all reference type on heap. This help runtime environment to create an object graph and keep track of what all objects are not in use and can be considered for garbage collection.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.