SlideShare a Scribd company logo
1 of 8
Stack and Heap Allocation
Program Address Space
   Any program you run has, associated with it, some memory
    which is divided into:
       Code Segment
       Data Segment (Holds Global Data)
       Stack (where the local variables and other temporary information
        is stored)
       Heap                   The Heap grows         Heap
                              downwards




                              The Stack grows        Stack
                              upwards

                                                   Data Segment


                                                   Code Segment
Local Variables:Stack Allocation
   When we have a declaration of the form “int a;”:
     a variable with identifier “a” and some memory allocated to it is
         created in the stack. The attributes of “a” are:
          Name: a
          Data type: int
          Scope: visible only inside the function it is defined, disappears
             once we exit the function
          Address: address of the memory location reserved for it. Note:
             Memory is allocated in the stack for a even before it is
             initialized.
          Size: typically 4 bytes
          Value: Will be set once the variable is initialized
   Since the memory allocated for the variable is set in the beginning
    itself, we cannot use the stack in cases where the amount of memory
    required is not known in advance. This motivates the need for HEAP
Pointers
   We know what a pointer is. Let us say we have declared a
    pointer “int *p;” The attributes of “a” are:
       Name: p
       Data type: Integer address
       Scope: Local or Global
       Address: Address in the data segment or stack segment
       Size: 32 bits in a 32-bit architecture
   We saw how a fixed memory allocation is done in the stack,
    now we want to allocate dynamically. Consider the declaration:
       “int *p;”. So the compiler knows that we have a pointer p that
        may store the starting address of a variable of type int.
       To point “p” to a dynamic variable we need to use a declaration of
        the type “ p = new int;”
Pointers : Heap Allocation
   Dynamic variables are never initialized by the compiler, so it is
    a good practice to initialize it.
                          int *p;
                          p = new int;
                          *p = 0;



   In more compact notation:


                          int *p = new int(0);
More on Heap
   Internal representation of the earlier declaration would be as
    follows:
                                                  FE12

                 p      FE12              *p       0

                Pointer variable: Data   Dynamic variable: Heap
                      Segment



   Now we can delete the dynamic variable from the heap using
       “delete p;” Now 2 bytes of memory were freed but the pointer p
        isnit erased and it can be used to initialize another dynamic
        variable.
Arrays on Heap
   C++ also allows us to allocate arrays in heap. This can be done
    as follows:
                      int *ap = new int[20];




   To initialize the array, we do the following

                      for (int i =0; i <=19; i++)
                      ap[i] = 0;
Be wary of….
   Deleting a dynamic variable that has already been Deleted
                    int *p = new int(0);
                    delete p;
                    delete p;

   Deleting a dynamic variable that has not yet been allocated
                     int *p = new int(0);

   Assign value to an unallocated dynamic variable
                  char *p;
                  StringCopy(p, ‘Hello’);

   Assigning a value to a deleted dynamic variable

                   char *str = new char[100];
                   delete [] str;
                   char *test = new char[100];
                   strcpy(str, "surprise !");
                   cout << test;
                   delete [] test;

More Related Content

What's hot

Microcontroller 8051
Microcontroller 8051Microcontroller 8051
Microcontroller 8051
John Williams
 
Modes of 80386
Modes of 80386Modes of 80386
Modes of 80386
aviban
 

What's hot (20)

Applet programming
Applet programming Applet programming
Applet programming
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
8086 pin details
8086 pin details8086 pin details
8086 pin details
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Frame buffer
Frame bufferFrame buffer
Frame buffer
 
Java interface
Java interfaceJava interface
Java interface
 
Code generation
Code generationCode generation
Code generation
 
Introduction to Garbage Collection
Introduction to Garbage CollectionIntroduction to Garbage Collection
Introduction to Garbage Collection
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
Microcontroller 8051
Microcontroller 8051Microcontroller 8051
Microcontroller 8051
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Modes of 80386
Modes of 80386Modes of 80386
Modes of 80386
 
Embedded _c_
Embedded  _c_Embedded  _c_
Embedded _c_
 
Finalize() method
Finalize() methodFinalize() method
Finalize() method
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
Lexical analyzer generator lex
Lexical analyzer generator lexLexical analyzer generator lex
Lexical analyzer generator lex
 

Viewers also liked

Viewers also liked (12)

Embeddedsystem
EmbeddedsystemEmbeddedsystem
Embeddedsystem
 
Stack and Heap
Stack and HeapStack and Heap
Stack and Heap
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Stack & heap
Stack & heap Stack & heap
Stack & heap
 
Fix Heap corruption in Android - Using valgrind
Fix Heap corruption in Android - Using valgrindFix Heap corruption in Android - Using valgrind
Fix Heap corruption in Android - Using valgrind
 
Operating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - ProcessesOperating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - Processes
 
Memory allocation
Memory allocationMemory allocation
Memory allocation
 
Advanced C
Advanced C Advanced C
Advanced C
 
Process of operating system
Process of operating systemProcess of operating system
Process of operating system
 
Operating system - Process and its concepts
Operating system - Process and its conceptsOperating system - Process and its concepts
Operating system - Process and its concepts
 
Von Neumann vs Harvard Architecture
Von Neumann vs Harvard ArchitectureVon Neumann vs Harvard Architecture
Von Neumann vs Harvard Architecture
 
Memory management in Linux
Memory management in LinuxMemory management in Linux
Memory management in Linux
 

Similar to Stack and heap allocation

Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
tech4us
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
Edward Chen
 

Similar to Stack and heap allocation (20)

C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
Linked list
Linked listLinked list
Linked list
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
Pointer
PointerPointer
Pointer
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Lecture 2 java.pdf
Lecture 2 java.pdfLecture 2 java.pdf
Lecture 2 java.pdf
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Chapter16 pointer
Chapter16 pointerChapter16 pointer
Chapter16 pointer
 
Pointer in c++ part3
Pointer in c++ part3Pointer in c++ part3
Pointer in c++ part3
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 

Stack and heap allocation

  • 1. Stack and Heap Allocation
  • 2. Program Address Space  Any program you run has, associated with it, some memory which is divided into:  Code Segment  Data Segment (Holds Global Data)  Stack (where the local variables and other temporary information is stored)  Heap The Heap grows Heap downwards The Stack grows Stack upwards Data Segment Code Segment
  • 3. Local Variables:Stack Allocation  When we have a declaration of the form “int a;”:  a variable with identifier “a” and some memory allocated to it is created in the stack. The attributes of “a” are:  Name: a  Data type: int  Scope: visible only inside the function it is defined, disappears once we exit the function  Address: address of the memory location reserved for it. Note: Memory is allocated in the stack for a even before it is initialized.  Size: typically 4 bytes  Value: Will be set once the variable is initialized  Since the memory allocated for the variable is set in the beginning itself, we cannot use the stack in cases where the amount of memory required is not known in advance. This motivates the need for HEAP
  • 4. Pointers  We know what a pointer is. Let us say we have declared a pointer “int *p;” The attributes of “a” are:  Name: p  Data type: Integer address  Scope: Local or Global  Address: Address in the data segment or stack segment  Size: 32 bits in a 32-bit architecture  We saw how a fixed memory allocation is done in the stack, now we want to allocate dynamically. Consider the declaration:  “int *p;”. So the compiler knows that we have a pointer p that may store the starting address of a variable of type int.  To point “p” to a dynamic variable we need to use a declaration of the type “ p = new int;”
  • 5. Pointers : Heap Allocation  Dynamic variables are never initialized by the compiler, so it is a good practice to initialize it. int *p; p = new int; *p = 0;  In more compact notation: int *p = new int(0);
  • 6. More on Heap  Internal representation of the earlier declaration would be as follows: FE12 p FE12 *p 0 Pointer variable: Data Dynamic variable: Heap Segment  Now we can delete the dynamic variable from the heap using  “delete p;” Now 2 bytes of memory were freed but the pointer p isnit erased and it can be used to initialize another dynamic variable.
  • 7. Arrays on Heap  C++ also allows us to allocate arrays in heap. This can be done as follows: int *ap = new int[20];  To initialize the array, we do the following for (int i =0; i <=19; i++) ap[i] = 0;
  • 8. Be wary of….  Deleting a dynamic variable that has already been Deleted int *p = new int(0); delete p; delete p;  Deleting a dynamic variable that has not yet been allocated int *p = new int(0);  Assign value to an unallocated dynamic variable char *p; StringCopy(p, ‘Hello’);  Assigning a value to a deleted dynamic variable char *str = new char[100]; delete [] str; char *test = new char[100]; strcpy(str, "surprise !"); cout << test; delete [] test;