Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

What is heap and stack ?

  Asked By: Jeff    Date: Jul 14    Category: Java    Views: 692

I am a beginner in java. I am quite confuse with the term heap
and stack, can anyone pls explain what they are?



2 Answers Found

Answer #1    Answered By: Willard Washington     Answered On: Jul 14

These are the types of memory.......

Answer #2    Answered By: Emily Brown     Answered On: Jul 14

you dont need to know the difference.

From c.ittoolbox.com/documents/document.asp?i=2112

Traditionally in a process address space you would see stack  growing
upside down and heap  growing upwards. An application wise difference is
all the memory allocated dynamically gets allocated on heap viz. malloc
free, calloc etc. The stack of an process contains stack frames(
containing the return address linkage for a function and the data
in a stack which has the qualifier 'auto').

Efficiency-wise, one thing I can think of is memory on stack should be a
bit faster to access as the hit-ratio for the pages having stack memory
should have a better chances in terms of cache and also virtual memory.
There should be a few more here, which can be same as choice of using
array vs new().

2. Adapted from response by S.H.Bouwhuis on Monday, July 07, 2003

Of course you are completely right. But, I think a fair warning to
thinking of using the stack as general storage is: DON'T!

-- The stack is basically a queue which gets (over-)written a lot. It is

really intended for function parameters and return codes. Better yet, I
would even suggest not having any parameters in functions which are big
(for instance a struct or a class).

Class CMyClass
int32 pi32Array[100000];

I would suggest using MyFunc(const CMyClass *pMyClassObj), which takes
only n-bit on the stack (on a n-bit machine, e.g. 32-bit), instead of at
least 100000 bytes (in this case).

Also, there is no save way to protect the stack space from being
overwritten (other than adjusting the ESP register yourself).

In conclusion, unless you're coding in assembly, don't use the stack for
general data.

More information:
More information on the C++ programming language is available in the
mail list archives. Enter a Topic and click the search button for

Didn't find what you were looking for? Find more on What is heap and stack ? Or get search suggestion and latest updates.