Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

[noob][c++] heap and stack

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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

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…
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 learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
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.

860 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