Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
Allocation of memory for objects in C++ - Stack v Heap

In C++, memory is allocated to variables on a stack or on a heap. Allocated on the stack, the variable persists until the end of the block in which it's defined. Allocated on the heap, the memory containing the object persists until the end of your program, or until you delete the object.

Stack memory is set up by a simple variable declaration as shown in the example:

  Train * serviceStack() {
    Train later(3,79);
    cout << "Created with capacity of " << later.getCapacity() << endl;
    return &later;
    }


And heap memory through the use of the new keyword:

  Train * serviceHeap() {
    Train * early = new Train(2,75);
    cout << "Created with capacity of " << early->getCapacity() << endl;
    return early;
    }


The stack example here is very, very bad indeed as the returned address points to memory on the stack which will be re-used in subsequent code as the program progresses after the return from the function.

Here's code calling our functions above:

  Train * first = serviceHeap();
  Train * second = serviceStack();
  
  int e = first->getCapacity();
  cout << "Capacity of " << e << endl;
  
  int c = second->getCapacity();
  cout << "Capacity of " << c << endl;


and the result of running that code:

  Created with capacity of 210
  Created with capacity of 331
  Capacity of 210
  Capacity of -678813632


Within the methods used to create the objects, teh references to the getCapacity method both return the correctly calculated value. Once the creating methods have been exited, the object that's on the heap (the first one) continues to exist and function correctly, whereas the object that wason the stack has pobably been overwritten with something else, and results are "random". Run it again:

  Created with capacity of 210
  Created with capacity of 331
  Capacity of 210
  Capacity of -395132864


Many modern compilers will flag a warning if they spot you coding in this way:

  WomanWithCat:harwell grahamellis$ g++ -o objects_bothways objects_bothways.cpp
  objects_bothways.cpp:26:10: warning: address of stack memory associated with local variable
    'later' returned [-Wreturn-stack-address]
      return &later;
              ^~~~~
  1 warning generated.
  WomanWithCat:harwell grahamellis$


General rule:

Stack variables for temportary objects, heap for persistant ones

Source code of full example [here]. Subject covered on our Learning to program in C++ amd C++ programming courses.
(written 2015-10-31)

 
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
C232 - C and C based languages - Defining and using classes in C++
  [1925] Introduction to Object Oriented Programming - (2008-12-06)
  [2577] Complete teaching example - C++, inheritance, polymorphism - (2010-01-15)
  [2578] Where are your objects stored in C++? - (2010-01-16)
  [2579] Creating, setting up and using objects in C++ - (2010-01-16)
  [3250] C++ - how we teach the language and the concepts behind the language - (2011-04-17)
  [3716] Learning C++ - a design pattern for your first class - (2012-05-02)
  [3721] Naming blocks of code, structures and Object Orientation - efficient coding in manageable chunks - (2012-05-06)
  [3810] Reading files, and using factories to create vectors of objects from the data in C++ - (2012-07-21)
  [3978] Teaching OO - how to avoid lots of window switching early on - (2013-01-17)
  [4129] Simple OO demonstration in C++, comparison to Python - (2013-07-01)
  [4372] Template / design pattern for C++ constructor and accessors - (2014-12-29)


Back to
Perl, PHP, Python, Lua, Tcl, C++, Ruby - final public courses for 2015
Previous and next
or
Horse's mouth home
Forward to
C - why is slow to write and debug) but fast to run?
Some other Articles
Lua - changes to how integers and floats are handled - 5.2 to 5.3
Moderation - and the tendency to over-moderate
Japanese and Malaysian food in Melksham
C - why is slow to write and debug) but fast to run?
Allocation of memory for objects in C++ - Stack v Heap
Perl, PHP, Python, Lua, Tcl, C++, Ruby - final public courses for 2015
Formatting and outputting your own classes in C++
Left shift operator on an output stream object - C++
Hello World in C++ - a first program, with the process explained
Variables, Pointers and References - C and C++
4759 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2024: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/4565_All ... -Heap.html • PAGE BUILT: Sun Oct 11 16:07:41 2020 • BUILD SYSTEM: JelliaJamb