473,625 Members | 2,853 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"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 6717
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

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

Similar topics

24
2853
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 a class called polynomial. Its a nothing little class right now, with just int variables, a basic container class. Im using it as I go through some tutorials, but in this particular tutorial its telling me to do polynomial *first = new...
10
1918
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 correct me If I am wrong..
53
26358
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 variable? My answer: static variable in function and global variable are allocated in head, and automatic variable is allocated in stack. Right?
94
30265
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 Statement (C# Reference) statement to serialize access. " But when is it better to use "volatile" instead of "lock" ?
6
2925
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 fault) raised in your program"
11
1888
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
11679
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 one, and in what percentage of your projects is one used? I have never used one in personal or professional C++ programming. Am I a holdover to days gone by?
0
8253
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8189
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8692
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8354
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8497
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5570
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4089
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1802
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1499
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.