473,416 Members | 1,721 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

"heap" vs "stack"

Can someone explain what a heap and what a stack is? And why I should
care? I used to know, but then I forgot. And I can't seem to find it
in the C++ FAQ.

I keep reading how allocating from the heap is slow or something, and I
have no idea why that would be.

Joe
Apr 14 '06 #1
15 6697
Joe Van Dyk wrote:
Can someone explain what a heap and what a stack is? And why I should
care? I used to know, but then I forgot. And I can't seem to find it
in the C++ FAQ.
A "heap" is usually a relatively unorganized data repository. A "stack"
is a quite ordered data container with elements queued up in the "first in
-- last out" manner.
I keep reading how allocating from the heap is slow or something, and
I have no idea why that would be.


In more loose lingo than C++ Standard uses, "heap" is the synonym for the
free store, and "stack" is the place where objects with automatic storage
duration are allocated.

V
--
Please remove capital As from my address when replying by mail
Apr 14 '06 #2
Joe Van Dyk wrote:
Can someone explain what a heap and what a stack is? And why I should
care? I used to know, but then I forgot. And I can't seem to find it in
the C++ FAQ.
A stack is a data structure that runs Last In First Out. That's so efficient
and convenient that CPUs generally implement a stack in hardware, so
functions can park their local variables on it. When they call servant
functions, these add their variables to the current head of the stack, then
point the head to the next spot after their variables. So that's how
functions can call functions, each keeping private variables for as long as
each function runs.

A heap is simply the opposite of a stack. You can allocate and de-allocate
arbitrarily sized chunks of heap, in an arbitrary order.
I keep reading how allocating from the heap is slow or something, and I
have no idea why that would be.


A heap must perform much more work at allocation and deallocation time. It
searches for a good unused region, checks this is larger than the requested
size, writes markers around the block to reserve it, fixes up other markers
in the heap to point correctly, and returns a pointer to the block. When it
gets the block back from the program, it erases the markers, and fixes up
the other markers.

A good alternative is a custom heap that returns fixed sized blocks. That's
orders of magnitude faster. If each block is larger than a pointer, then the
heap can store its list of free blocks directly into storage area. Each free
block contains a pointer to the next free block.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Apr 14 '06 #3
"Phlip" writes:
A heap is simply the opposite of a stack.


Much like a lizard is simply the opposite of a nuclear reactor?
Apr 14 '06 #4
bb
MyClass object1; // creates the object in stack

MyClass *object2 = new MyClass(); // creates the object in heap

When you create an object in stack, memory is managed automatically for
you i.e., memory is released as soon as it goes out of scope.

When you create an object in the heap, it is your RESPONSIBILITY to
release the memory as soon as you are finished with it by calling
'delete' or else it leads to memory leak.

'heap' helps you to allocate memory dynamically at run time.

BTW, in Java, you cannot allocate objects in the stack.

Apr 14 '06 #5
bb wrote:
MyClass object1; // creates the object in stack
I didn't get the impression that the above "created" anything anywhere.

I got the impression that it's purely a definition so the compiler knows
the data type, when it finds "object1" later in the program. object1 is
first created when it's first used I think..
MyClass *object2 = new MyClass(); // creates the object in heap


Agreed.
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Apr 14 '06 #6
Allocating from the heap is slow because it involves system calls in
whatever operating system that you are using. When using the stack,
everything is setup at compile time, and you do not have to make system
calls. Variables declared on the stack are automatically deleted for
you when they go out of scope. Variable declared on the heap must be
explicitly deleted when finished or there will be a memory leak.

Cheers,
Mark

Apr 14 '06 #7

Martin Jørgensen wrote:
bb wrote:
MyClass object1; // creates the object in stack
I didn't get the impression that the above "created" anything anywhere.


It does.
I got the impression that it's purely a definition so the compiler knows
the data type, when it finds "object1" later in the program. object1 is
first created when it's first used I think..


A definition *is* the creation of something. You might be confusing the
concepts of definition and declaration.

That statment is both the declaration of object1 (introduction of the
name object1 and its type) and definition of object1 (actual creation
of the object). The default constructor of MyClass will be called to
construct object1 in that statement, not at some later point.

Gavin Deane

Apr 14 '06 #8
Martin Jørgensen wrote:
bb wrote:
MyClass object1; // creates the object in stack
I didn't get the impression that the above "created" anything
anywhere.


It depends on where that statement appears. If it appears in a class
definition, then it's a mere declaration. If it appears outside of any
class definition, then it's a declaration _and_ a definition (and also
default-initialisation).

The "stack vs. not stack" is debatable. If the statement appears outside
of any function scope, it's not stack, usually.
I got the impression that it's purely a definition so the compiler
knows the data type, when it finds "object1" later in the program.
object1 is first created when it's first used I think..


No. The semantic rule is that it's created where it's defined. For all
intents and purposes, it may never be "used". Yet, it has to exist because
it will be destroyed.
MyClass *object2 = new MyClass(); // creates the object in heap


Agreed.


Yet, it creates the 'object2' _pointer_ elsewhere.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 14 '06 #9
Gavin Deane wrote:
Martin Jørgensen wrote:

bb wrote:
MyClass object1; // creates the object in stack
I didn't get the impression that the above "created" anything anywhere.

It does.

I got the impression that it's purely a definition so the compiler knows
the data type, when it finds "object1" later in the program. object1 is
first created when it's first used I think..

A definition *is* the creation of something. You might be confusing the
concepts of definition and declaration.


Oh, yeah...... Ofcourse...
That statment is both the declaration of object1 (introduction of the
name object1 and its type) and definition of object1 (actual creation
of the object). The default constructor of MyClass will be called to
construct object1 in that statement, not at some later point.


Oh, yeah... I remember that now...
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Apr 14 '06 #10
>> MyClass object1; // creates the object in stack
I didn't get the impression that the above "created" anything anywhere. I got the impression that it's purely a definition so the compiler knows
the data type, when it finds "object1" later in the program. object1 is
first created when it's first used I think..


Assuming that this declaration is in the scope of a function, it will
create object1 on the stack. If the declaraion is in a cpp file, but
outside the scope of a function, it will be allocated from the heap at
initialization time. If this is in a header file as part of a class
definition, then it is used by the compiler to determine the size of
the class that is being defined. In that case, object1 would only be
created when the class that contains it is instantiated, either on the
stack or heap.

Cheers,
Mark

Apr 14 '06 #11
Phlip wrote:
Joe Van Dyk wrote:

Can someone explain what a heap and what a stack is? And why I should
care? I used to know, but then I forgot. And I can't seem to find it in
the C++ FAQ.

A stack is a data structure that runs Last In First Out. That's so efficient
and convenient that CPUs generally implement a stack in hardware, so
functions can park their local variables on it. When they call servant
functions, these add their variables to the current head of the stack, then
point the head to the next spot after their variables. So that's how
functions can call functions, each keeping private variables for as long as
each function runs.

A heap is simply the opposite of a stack. You can allocate and de-allocate
arbitrarily sized chunks of heap, in an arbitrary order.

I keep reading how allocating from the heap is slow or something, and I
have no idea why that would be.

A heap must perform much more work at allocation and deallocation time. It
searches for a good unused region, checks this is larger than the requested
size, writes markers around the block to reserve it, fixes up other markers
in the heap to point correctly, and returns a pointer to the block. When it
gets the block back from the program, it erases the markers, and fixes up
the other markers.

A good alternative is a custom heap that returns fixed sized blocks. That's
orders of magnitude faster. If each block is larger than a pointer, then the
heap can store its list of free blocks directly into storage area. Each free
block contains a pointer to the next free block.


Ah, that's right. It's all flooding back to me now. omg, now I even
remember something called tail-recursion (or something like that).

Thanks everyone,
Joe
Apr 14 '06 #12
Dnia 14 Apr 2006 07:18:03 -0700, ma*****@gmail.com napisa³(a):
Allocating from the heap is slow because it involves system calls in
whatever operating system that you are using. When using the stack,
everything is setup at compile time, and you do not have to make system
calls. Variables declared on the stack are automatically deleted for
you when they go out of scope. Variable declared on the heap must be
explicitly deleted when finished or there will be a memory leak.


But what about static 'local' (inside of functions/methods) variables?
These are exceptions from this rule - these are allocate on heap first time
they are used (until then these are declarations), yet You can't delete
these explicitly... an interesting exception to above rule :)

--
..:-Dad, do you think there's people on other planets? :.
..:-I don't know, Sparks. But I guess I'd say if it is just us...seems like:.
..: an awful waste of space. : JID: zodiaq(at)jabber.aster.pl Zodiaq ]] :.
Apr 18 '06 #13
Zodiaq wrote:
But what about static 'local' (inside of functions/methods) variables?
These are exceptions from this rule - these are allocate on heap first time
they are used (until then these are declarations), yet You can't delete
these explicitly... an interesting exception to above rule :)


Actually, static locals are NOT allocated from either heap nor stack
at runtime. They are typically part of the initial data allocation
when the program loads.

You're confusing allocation with initialization.
Apr 18 '06 #14
Ron Natalie wrote:
But what about static 'local' (inside of functions/methods)
variables? These are exceptions from this rule - these are allocate
on heap first time they are used (until then these are
declarations), yet You can't delete these explicitly... an
interesting exception to above rule :)
Actually, static locals are NOT allocated from either heap nor stack
at runtime. They are typically part of the initial data allocation
when the program loads.


....which is not to say they are not allocated from free store. It is
unspecified how, or where from, the memory for them is obtained.
[..]


V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 18 '06 #15

Zodiaq wrote:
Dnia 14 Apr 2006 07:18:03 -0700, ma*****@gmail.com napisa³(a):
Allocating from the heap is slow because it involves system calls in
whatever operating system that you are using. When using the stack,
everything is setup at compile time, and you do not have to make system
calls. Variables declared on the stack are automatically deleted for
you when they go out of scope. Variable declared on the heap must be
explicitly deleted when finished or there will be a memory leak.


But what about static 'local' (inside of functions/methods) variables?
These are exceptions from this rule - these are allocate on heap first time
they are used (until then these are declarations), yet You can't delete
these explicitly... an interesting exception to above rule :)


A static variable is usually taken care of by a linker. Most unix
linker will put a static variable in the so called 'BSS' (block started
by symbol) segment where a variable only has its symbol and storage but
not its initial value. This is practical implementation detail and not
c++ relevant. A static variable is thus allocated by the
compiler/linker and stays static during runtime.

Apr 19 '06 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
by: Rv5 | last post by:
Rookie c++ question, but Ive spent the last 5 years doing Java, where everytime I created an object I used new. In c++ I can create my objects without and its confusing me just a little. I have...
10
by: Amit | last post by:
char *str1="amit"; char str2="mehta" strcat(str1,str2); It will crash, I feel str1 will be stored in code section. Once memory is allocated, you cannot change or append into this. Please...
53
by: fdmfdmfdm | last post by:
This is an interview question and I gave out my answer here, could you please check for me? Q. What are the memory allocation for static variable in a function, an automatic variable and global...
94
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock...
6
by: hadad.yaniv | last post by:
Hello, i am new to c++, i hav a vector of typed object: vector<Man*People; When i do a second pushback, even for the same object the program crash say: "An Access Violation (Segmentation...
11
by: Bob Altman | last post by:
Hi all, I want to write a generic class that does this: Public Class X (Of T) Public Sub Method(param As T) dim x as T = param >3 End Sub End Class
350
by: Lloyd Bonafide | last post by:
I followed a link to James Kanze's web site in another thread and was surprised to read this comment by a link to a GC: "I can't imagine writing C++ without it" How many of you c.l.c++'ers use...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.