Archive

Posts Tagged ‘pointers’

Heap vs. Stack in C++

March 20th, 2009 bodom_lx 4 comments

After the study of pointers versus references, the second natural question that comes in head of a ex Java developer turning to C++ is:

“What are the difference between static and dynamic memory allocation in C++?”

which can be translated as:

“When should I use the stack and when do I have to use the heap in C++?”

that can be further simplified to:

“When should I use the new operator in C++?”

I could simply summarize the answer to: “Use stack when possible”, but I think that this time there is the need of more explanations. Let’s have the following model for a process in the system:

A simplified model for a process

A simplified model for a process

I’m not really interested in an real representation of a process (see Modern Operating Systems by A. S. Tanenbaum for a very good explanation on processes), but focus on the stack and on the heap.
In reality the heap is a software abstraction but you can also imagine it like the stack.
In C++ programs there are also several other memory areas in which objects and non-object values may be stored (see this article on GotW for further details).

Why then choose between stack or heap? Quoting my publication on object-oriented memory management in Java:

Stack-based variables have their extent determined by their scope, so the former is constrained by the structure of the code at compile-time .

Sometimes there is a need for the variables with unconstrained extent in order to cope with
problems where lifetime of a variable can only be known at run-time.
In this case heap-based variables, whose extent is strictly under control of the programmer, are used. [..]

I promise that I will update my 17 pages about OO-memory management to cover also C++ by the end of June. By the way, following some forums, wikipedia, my publication and GotW, I also summarized pros and cons of stack and heap use in C++:

Stack Heap
Its size is determined at compile-time Size determined at run-time
Therefore, it is less expensive and quick Therefore, it is more expensive and slower than stack
The preferred way to store objects and variables if their size is limited. To be used only if needed: the amount of memory needed is variable and unknown, and may increase rapidly.
There is an AUTOMATIC CLEANUP of objects when they go out of their scope Objects STAY IN MEMORY even when you don’t use them anymore.
Programmers don’t have to bother to free resources Therefore, programmers HAVE TO CLEAN memory manually. However, all modern OS free the resources when the program exits.

Update 2009-07-03
After 4 months of heavy GUI and Database C++ programming, here are my thoughts: if you are planning to write a program with something more than a couple of objects interacting, using associations and therefore, objects as attributes, use the heap. Every serious program, even if not really big, uses heap for object allocation. Just take care to delete the objects when you don’t need them anymore. Objects on the heap are dynamically allocated and it is more comfortable to pass them through other objects using pointers. The use of the heap assures the live of objects even if the method that generated them runs out of scope ( =dies ). If you also plan to write GUIs, solid toolkits like QT recommend the use of heap to create graphical objects.

In some Operating Systems, stack is also very limited while heap is usually not.

Here are listed the sources I used for writing this article:

  • http://www.velocityreviews.com/forums/t278261-stack-vs-heap.html
  • http://www.computing.net/answers/programming/stackheap-c/2293.html
  • http://www.codeguru.com/forum/showthread.php?p=1186307#post1186307
  • http://www.codeguru.com/forum/showthread.php?t=350945
  • http://www.gotw.ca/gotw/009.htm
  • http://en.wikipedia.org/wiki/Process_(computing)#Representation
  • http://task3.cc/object-oriented-memory-management/

Hope that this article helped you to clearly understand the differences between stack and heap allocation in C++, write me if there are other issues or you need more explanations!

Related posts

Reference vs. Pointer

March 18th, 2009 bodom_lx No comments

In Software Engineering Project course we need to learn some C++ to develop the project. A question that some programmers have when passing from Java to C++ (like me) is “Which are the differences between pointers and references?“. You can find a lot of answers around developers forum, but I summarized them in the following table. Glad if you found it useful!

Reference Pointer
is an object which IS AN ALIAS for another object is an object that CONTAINS THE ADRRESS IN MEMORY of another object
the preferred way of undirectly access objects you should use it just if you really need it, as it lets you to work in a lower level than a reference does
keeps your code clear the code is less clear but still understandable
it must be initialized when created you don’t have to initialize it when declared
it references to the one object and only that one, therefore you can not modify the address referenced because it contains an address, it can point to many different objects during lifetime. The address can be manipulated
when used, the address is dereferenced without using any particular operator the address must be dereferenced using the * operator

Related posts

Object Oriented Memory Management

March 19th, 2008 bodom_lx No comments

Major Update on 10th April 2009, inclusion of C++ programming language!
Updated on 18th April 2008, a complete example on stack and heap
Updated on 15th April 2008, new contents and new layout!
Updated on 6th April 2008, new contents!

The paper you can download from here is about a model for memory management during the execution of programs written in Java and C++.

It started on March, 2008 as a summary of the lecture notes of both the “Programming Project” and
“Software Engineering Project” courses held by professors of the CASE (Center for Applied Software Engineering) of the Free University of Bolzano – Bozen.

The first versions of this publication were only about Java memory management.
Subsequent revisions added information found on other sources. Unfortunately, the author forgot to
reference the sources on the document.

On March, 2009 the author began to add the information about C++ programming language. More
information from other sources were added, including their attribution.

The biggest source of this document is still the set of presentations of CASE.
The code snippets and their corresponding stack/heap diagrams are copied in full from those of the
slides.

The next major revision will contain original images (not belonging to CASE slides), as well as other code
snippets that I could find more clear than those of CASE.

If you find that this document contains information taken from one of your publications, please
contact the author, that is willing to either delete them from this document or to add an attribution to
your work.

Download the PDF of the summary

Table of Contents:

  • The model
  • Code load and execution
  • Activation Record (AR)
  • Contents of the Activation Record
  • Abbreviations for
  • Declaration vs. Definition
  • The scope of a variable
  • Extent of a Variable
  • Blocks
  • Scope Activation Record (SAR)
  • Example on SAR
  • Role of SLs
  • Dynamic Memory Allocation And Handling
  • Dynamic Vs. Static memory allocation
  • Dynamic Memory Scope and Extent
  • Accessing dynamic memory
  • Classes
  • Objects
  • Object instantiation
  • Objects in Memory (Java)
  • Objects in Memory (C++)
  • Memory Management issues (Java)
  • Memory Management issues (C++)
  • Methods
  • Methods (Java)
  • Methods (C++)
  • Attributes
  • The null value (Java)
  • The NULL value (C++)
  • Parameter
  • Parameter Passing (Java)
  • Example of parameters passing (Java)
  • Example of parameters passing (Java), continued
  • Parameter Passing (C++)
  • Example of parameters passing by value (C++)
  • Example of parameters passing by reference (C++)
  • Pointers vs. Parameters (C++)
  • Previous example using pointers (C++)
  • Constructor
  • Inline initialization
  • A constructor’s call (Java)
  • Class attributes
  • Example of class attributes (Jav)
  • Example of class attributes (C++)
  • Class Method
  • Example of Stack/Heap Diagrams in Java
  • Code
  • Stack Diagram
  • Heap Diagram
  • Memory portions assigned to a program (code area, heap / dynamic memory area), execution stack
  • How code is loaded in Java
  • The Activation Record (AR) and function calls
  • Abbrevations (AR, RV, RA, SP, N/E, @, ??, arb)
  • Examples on method calls and activation records usage
  • Declaraion vs. Definition of a variable, the scope of a variable, blocks
  • Scope Activation Record (SAR), Static Link (SL), the role of SL
  • The extent/lifetime of a variable
  • Dynamic memory allocation and handling
  • Dynamic vs. Static memory allocation
  • Dynamic memory scope and extent
  • Accessing dynamic memory
  • Classes and Objects in detail, object instantiation
  • Memory Management issues
  • Objects vs. Variables (definitions)
  • Methods of Objects
  • Class Attributes
  • The null value
  • Parameters (formal, actual), parameters passing (by reference, by value)
  • Constructors and Inline Initialization
  • Constructor’s call
  • Class attributes (static variables)
  • Class methods (static methods)
  • Complete Example of Stack/Heap Diagrams

Everything is integrated with simple examples.

Download the PDF of the summary

Related posts

Sorting array elements with C language

February 23rd, 2008 bodom_lx 3 comments

UPDATE 17:19: it seems that the program I implemented today uses a kind of Bubble Sort algorithm, give it a try, it’s quite interesting!

After 3 long days studying C, I think I’ve assimilated a good knowledge base for the incoming semester.
So there is a tiny C program that sorts the elements of a given integer array, using pointers:

Download the source code (well commented)

#include <stdio.h>
void sortArray(int *firstElement, int *lastElement);
void swapArrayElements(int *firstElement, int *secondElement);
void printArray(int array[], int arraySize);

void sortArray(int *firstElement, int *lastElement){
        int *currentElement = firstElement;
        while (firstElement != lastElement){
                while(currentElement != lastElement){
                        if(*currentElement < *firstElement){
                                swapArrayElements(currentElement,firstElement);
                        }
                        currentElement++;
                }
                firstElement++;
                currentElement = firstElement;
        }
}

void swapArrayElements(int *firstElement, int *secondElement){
        int tmp;
        tmp = *firstElement;
        *firstElement = *secondElement;
        *secondElement = tmp;
}

void printArray(int array[], int arraySize){
        int counter = 0;
        while(counter<arraySize){
                printf("%d\n",array[counter]);
                counter++;
        }
}

int main (int argc, char *argv[]){
        int array[] = {2929393,1,23239,-66,15,4,3,0,112,45,3,1000,19};
        int arraySize = sizeof(array)/sizeof(array[0]);
        int *firstElement = &array[0];
        int *lastElement = firstElement + arraySize;
        printf("————————————————-\n");
        printf("Elements of the array:\n");
        printf("————————————————-\n");
        printArray(array,arraySize);
        printf("————————————————-\n");
        sortArray(firstElement,lastElement);
        printf("Elements sorted:\n");
        printf("————————————————-\n");
        printArray(array,arraySize);
        printf("————————————————-\n");
}

 

A better program should ask the user to input the array elements, and a better algorithm should not scan every array element n times, where n is the number of the elements.
But I wrote it just for fun and for learning C pointers. I will learn to do better in the Data Structures and Algorithms course in the next semester ;)

Related posts