Solved

[noob][c++] heap and stack

Posted on 2007-11-16
4
402 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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

776 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