Solved

[noob][c++] heap and stack

Posted on 2007-11-16
4
382 Views
Last Modified: 2010-04-01
what's the difference between heap and stack?


I read that most the time variables are on heap, so when their scope of existence ends, they ll be automatically deleted

but then there are cases when I can deliberately put things onto the stack (why would I do that?) and therefore must deliberately delete them when I finish with them.


so I need a destructor?


this is a sample code from
http://www.cplusplus.com/doc/tutorial/classes.html



how do I know when I am using heap and stack?




// example on constructors and destructors
#include <iostream>
using namespace std;

class CRectangle {
    int *width, *height;
  public:
    CRectangle (int,int);
    ~CRectangle ();
    int area () {return (*width * *height);}
};

CRectangle::CRectangle (int a, int b) {
  width = new int;
  height = new int;
  *width = a;
  *height = b;
}

CRectangle::~CRectangle () {
  delete width;
  delete height;
}

int main () {
  CRectangle rect (3,4), rectb (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}
0
Comment
Question by:Troudeloup
4 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 200 total points
ID: 20299432
Pretty simple: If you allocate memory using 'new', you are using the heap, otherwise the stack. As in your above code, 'CRectangle'  is allocated on the stack since no 'new' is used, whereas

  width = new int;
  height = new int;

is allocated on the heap.
0
 
LVL 14

Assisted Solution

by:cuziyq
cuziyq earned 100 total points
ID: 20299436
This is fundamentally incorrect.  When you instantiate an object like this:

Object foo;
foo.Init();

You've just created it on the stack.  When you instantiate an object like this:

Object *foo=new Object();  //Note the use of a pointer on this line
foo->init()  //Note the use of the dereference operatio -> instead of . as in the example above

You've just created it on the heap.

Always remember . . . anything created with new must be explicitly deleted.  Anything created with malloc must be explicitly freed.

Items on the stack get automatically cleaned up when they go out of scope.
0
 
LVL 20

Assisted Solution

by:ikework
ikework earned 100 total points
ID: 20299440
>>  (why would I do that?)

stack size is limited, if you need big objects/arrays, you have to create it on the heap

>> how do I know when I am using heap and stack?

here you see the difference:

int main()
{
    int a;// << this var is create on the stack

    int *p = new int[1000]; // << the memory for the array is created on the heap with the new-keyword

    delete[] p; // << free heap-space

    return 0;
}


ike

0
 
LVL 11

Assisted Solution

by:DeepuAbrahamK
DeepuAbrahamK earned 100 total points
ID: 20304515
Hi,

If you want more details on what is stack and heap, Heap space is of dynamic length and stack size is known at compile time. Items in stack space can be manipulated much faster than those on the heap.They're both memory, but they're different parts of memory. Stack space is quick to allocate and free since it merely involves increasing or decreasing the stack. Heap space requires something along the lines of Unix malloc() to track what's allocated and what's available. References to stack space may be slightly faster than to heap since stack references are invariably relative to a stack pointer register, but heap addresses have to be loaded from storage into a register before they can be used to reference the allocated memory.

Best Regards,
DeepuAbrahamK

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now