SlideShare une entreprise Scribd logo
1  sur  72
Télécharger pour lire hors ligne
Understanding
 Memory Management
and Garbage Collection
     Java and C++
                        Mohammad Shaker
                 FIT of Damascus - AI dept.
            MohammadShakerGtr@gmail.com
                    Programming Languages
What Is A Pointer?
NULL Pointer
Pointer Assignment
Shallow and Deep Copying
Bad Pointers
• When a pointer is first allocated, it does
  not have a pointee.
• The pointer is “uninitialized” or simply
  "bad".
• every pointer starts out with a bad
  value.
• There is nothing automatic that gives
  a pointer a valid pointee.
Bad Pointers




          IT IS NOT NULL!
Bad Pointers – Faster?!
• Most languages make it easy to omit
  this important step.
• The run-time checks are also a reason
  why such languages always run at
  least a little slower than a compiled
  language like C or C++!
Bad Pointers - Example
void BadPointer() {
int* p; // allocate the pointer, but not the pointee
*p = 42; // this dereference is a serious runtime error
}
Pointer Rules Summary
• A pointer stores a reference to its pointee. The
  pointee, in turn, stores something useful.
• The dereference operation on a pointer accesses its
  pointee. A pointer may only be dereferenced after
  it has been assigned to refer to a pointee. Most
  pointer bugs involve violating this one rule.
• Allocating a pointer does not automatically assign it
  to refer to a pointee. Assigning the pointer to refer
  to a specific pointee is a separate operation which
  is easy to forget.
• Assignment between two pointers makes them refer
  to the same pointee which introduces sharing.
Large Locals Example
void X() {
    int a = 1;
    int b = 2;
    // T1
    Y(a);
    // T3
    Y(b);
    // T5
}

void Y(int p) {
    int q;
    q = p + 2;
    // T2 (first time through)
    // T4 (second time through)
}
Large Locals Example
A bit harder - Bill Gates By Value
void B(int worth) {
   worth = worth + 1;
   // T2
}
void A() {
   int netWorth;
   netWorth = 55; // T1
   B(netWorth);
   // T3 -- B() did not change netWorth
}
A bit harder - Bill Gates By Value
void B(int worth) {
   worth = worth + 1;
   // T2
}
void A() {
   int netWorth;
   netWorth = 55; // T1
   B(netWorth);
   // T3 -- B() did not change netWorth
}
A bit harder - Bill Gates By Reference
void B(int &worth) {
   worth = worth + 1;
   // T2
}
void A() {
   int netWorth;
   netWorth = 55; // T1
   B(netWorth);
   // T3 -- B() did not change netWorth
}
A bit harder - Bill Gates By Reference
void B(int *worth) {
   *worth = *worth + 1;
   // T2
}
void A() {
   int netWorth;
   netWorth = 55; // T1
   B(&netWorth);
   // T3 -- B() did not change netWorth
}
Heap Memory
Heap!
• "Heap" memory, also known as
  "dynamic" memory.
• an alternative to local stack Memory.
Facts
• Local memory is quite automatic — it is
  allocated automatically on function call
  and it is deallocated automatically when
  a function exits.
• Heap Lifetime
  – Because the programmer now controls
    exactly when memory is allocated and
    deallocated, it is possible to build a data
    structure in memory, and return that data
    structure to the caller. This was never possible
    with local memory which was automatically
    deallocated when the function exited.
Heap - Allocation
• Allocate 3 GIF images in the heap
  each of which takes 1024 bytes of
  memory.
Heap - Deallocation
• Deallocating Gif2 image
Simple Heap Example
Simple Heap Example
Simple Heap Example
•   both values and the variables are allocated memory.
    However, each assignment copies into the variable’s block,
    not the contents of the value block, but instead its address
•   both values and the variables are allocated memory.
    However, each assignment copies into the variable’s block,
    not the contents of the value block, but instead its address
null.toString();
• we get a NullPointerException (Java)
• we can determine whether the value
  of a pointer variable is null or not, and
  hence, whether we can access its
  member.
• Multiple pointers sharing a value
Point p1 = new ACartesianPoint(50, 50);
Point p2 = p1;
p1.setX(100);
System.out.println(p2.getX());


• When p1 is assigned to p2, the pointer stored
  in p1 is copied into p2, not the object itself.
  Both variables share the same object, and thus, the
  code will print 100 and not 50, as you might expect.
Object Oriented Memory
      Management
      (Java and C++)
Foreknowledge
• A program address space:
  – Code area
  – Heap (Dynamic Memory Area)
  – Execution Stack
Foreknowledge
• Code area
  – where code to be executed is stored
• Heap
  – store variables and objects allocated
    dynamically
  – accessed with no restrictions
• Execution Stack
  – perform computation
  – store local variables
  – perform function call management
accessed with a LIFO policy (Last In First Out)
C++ Specific
• C++ has several other memory areas
• C++ the entire code is loaded into
  code area, and neglect dynamic
  loading.
Activation Record (AR)
void f(){
   g();
}
void g(){
   h();
}
void h(){
  k();
}
Activation Record (AR)
void f(){
   g();
}
void g(){
   h();
}
void h(){
  k();
}
Abbreviations for AR
•
Scope Activation Record (SAR)
   is put every time a new block is encountered
Scope Activation Record (SAR)
• Contains:
  – Local variables (declared inside the
    block)
  – The Static Link SL (a.k.a SAR link)
    a pointer to the SAR of the
    immediate enclosing block; used to acce
    ss local variables of outer blocks from the
    current block.
Scope Activation Record (SAR)
References and Pointers
   conceptually the SAME
Classes and Objects
Objects are instances of classes
Classes and Objects
Objects are instances of classes
 (Objects are classes in action)
C++ again
• In C++ classes are truly user defined ty
  pes. Objects are treated as any other
  variable and are allocated:
  – On the stack, as regular local variables
  – On the heap, like in Java
Java example

int[] hello = new int[5];
// reference hello is on stack, the object is on the
// heap.



hello[0] = 2;
// Java puts this value directly in same slot and doesn't
// create a wrapping object.




From: http://stackoverflow.com/questions/10820787/how-does-java-treat-primitive-type-arrays
Java: Why are wrapper classes needed?
 http://stackoverflow.com/questions/2134798/java-why-are-wrapper-classes-needed
Java example
public class CoffeeMaker {
       public CoffeeMaker(){}
}
..
..
CoffeeMaker aCoffeeMaker;
aCoffeeMaker = new CoffeeMaker();
int sugar = 4;
Integer sugarObject = new Integer(3);
Java example
public class CoffeeMaker {
       public CoffeeMaker(){}
}
..
..
CoffeeMaker aCoffeeMaker;
aCoffeeMaker = new CoffeeMaker();
int sugar = 4;
Integer sugarObject = new Integer(3);
Java example
• Java objects can be accessed just
  through reference variables, that hold
  the address of objects in heap.
C++ example
class CoffeeMaker {
   public:
      CoffeeMaker();
      virtual ~CoffeeMaker();
};

// ..
CoffeeMaker aCoffeeMaker;
CoffeeMaker *aPtrCoffeeMaker = new CoffeeMaker();
CoffeeMaker &aRefCoffeeMaker = aCoffeeMaker;
aRefCoffeeMaker = *aPtrCoffeeMaker; // dangerous!
int sugar = 4;
int *ptrSuger = new int;
int &aRefSugar = sugar;
C++ example
Stack and Heap comparison
Issues for objects in memory (Java)
• Objects with no references pointing to
  them are considered eligible for
  automatic garbage collection by the
  system, which runs periodically and
  performs the real destruction of the
  objects.
• GC is not directly under control of the
  programmer.
Issues for objects in memory (C++)
• After an object has been created on
  the heap (with the new directive) it
  survives until someone destroys it
  explicitly using the delete directive.
• This could lead to memory leaks
  – if the programmer forgets to delete
    objects no longer needed, they remain
    on the heap as wasted space
Methods (Java)
public class CoffeeMaker {
   public void prepareCoffee() {}
   public void prepareCoffeeSweet(int sugarAm){}
   void main(...) {
       CoffeeMaker aCoffeeMaker;
       aCoffeeMaker = new CoffeeMaker();
       aCoffeeMaker.prepareCoffee();
   }
}
Methods (Java)
public class CoffeeMaker {
   public void prepareCoffee() {}
   public void prepareCoffeeSweet(int sugarAm){}
   void main(...) {
       CoffeeMaker aCoffeeMaker;
       aCoffeeMaker = new CoffeeMaker();
       aCoffeeMaker.prepareCoffee();
   }
}
Methods (C++)
class CoffeeMaker {
   public:
       void prepareCoffee() {}
       void prepareCoffeeSweet(int sugarAm){}
       void main(...) {
           CoffeeMaker *aPtrCoffeeMaker;
           aPtrCoffeeMaker = new CoffeeMaker;
           aPtrCoffeeMaker-> prepareCoffee();
       }
}
Methods (C++)
class CoffeeMaker {
   public:
       void prepareCoffee() {}
       void prepareCoffeeSweet(int sugarAm){}
       void main(...) {
           CoffeeMaker *aPtrCoffeeMaker;
           aPtrCoffeeMaker = new CoffeeMaker;
           aPtrCoffeeMaker-> prepareCoffee();
       }
}
Understanding
Garbage Collection
Read!
•   http://www.simple-talk.com/dotnet/.net-framework/understanding-
    garbage-collection-in-.net/
•   http://en.wikibooks.org/wiki/C_Programming/Memory_management
•   (.pdf) Garbage Collection: Automatic Memory Management in the
    Microsoft .NET Framework
Dangerous Finalize()!
Keep goin’

Contenu connexe

Tendances

Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel Schulhof
WithTheBest
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
Sidd Singh
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handling
Hariz Mustafa
 

Tendances (20)

The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
C++11
C++11C++11
C++11
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel Schulhof
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
C++11 Multithreading - Futures
C++11 Multithreading - FuturesC++11 Multithreading - Futures
C++11 Multithreading - Futures
 
C++11
C++11C++11
C++11
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
A Taste of Dotty
A Taste of DottyA Taste of Dotty
A Taste of Dotty
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handling
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 

Similaire à Memory Management with Java and C++

Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 

Similaire à Memory Management with Java and C++ (20)

Return of c++
Return of c++Return of c++
Return of c++
 
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
JIT vs. AOT: Unity And Conflict of Dynamic and Static Compilers
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++
 
Graal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerGraal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT Compiler
 
Introduction to c part -3
Introduction to c   part -3Introduction to c   part -3
Introduction to c part -3
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
Dynamic Binary Analysis and Obfuscated Codes
Dynamic Binary Analysis and Obfuscated Codes Dynamic Binary Analysis and Obfuscated Codes
Dynamic Binary Analysis and Obfuscated Codes
 
Ahead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java ApplicationsAhead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java Applications
 
Appsec obfuscator reloaded
Appsec obfuscator reloadedAppsec obfuscator reloaded
Appsec obfuscator reloaded
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
test
testtest
test
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 

Plus de Mohammad Shaker

Plus de Mohammad Shaker (20)

12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate
 
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
 
Interaction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyInteraction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with Psychology
 
Short, Matters, Love - Passioneers Event 2015
Short, Matters, Love -  Passioneers Event 2015Short, Matters, Love -  Passioneers Event 2015
Short, Matters, Love - Passioneers Event 2015
 
Unity L01 - Game Development
Unity L01 - Game DevelopmentUnity L01 - Game Development
Unity L01 - Game Development
 
Android L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesAndroid L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and Wearables
 
Interaction Design L03 - Color
Interaction Design L03 - ColorInteraction Design L03 - Color
Interaction Design L03 - Color
 
Interaction Design L05 - Typography
Interaction Design L05 - TypographyInteraction Design L05 - Typography
Interaction Design L05 - Typography
 
Interaction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingInteraction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and Coupling
 
Android L05 - Storage
Android L05 - StorageAndroid L05 - Storage
Android L05 - Storage
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and Threading
 
Android L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSAndroid L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOS
 
Interaction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsInteraction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile Constraints
 
Interaction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsInteraction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and Grids
 
Android L10 - Stores and Gaming
Android L10 - Stores and GamingAndroid L10 - Stores and Gaming
Android L10 - Stores and Gaming
 
Android L06 - Cloud / Parse
Android L06 - Cloud / ParseAndroid L06 - Cloud / Parse
Android L06 - Cloud / Parse
 
Android L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesAndroid L08 - Google Maps and Utilities
Android L08 - Google Maps and Utilities
 
Android L03 - Styles and Themes
Android L03 - Styles and Themes Android L03 - Styles and Themes
Android L03 - Styles and Themes
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 

Dernier

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Dernier (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 

Memory Management with Java and C++

  • 1. Understanding Memory Management and Garbage Collection Java and C++ Mohammad Shaker FIT of Damascus - AI dept. MohammadShakerGtr@gmail.com Programming Languages
  • 2. What Is A Pointer?
  • 6. Bad Pointers • When a pointer is first allocated, it does not have a pointee. • The pointer is “uninitialized” or simply "bad". • every pointer starts out with a bad value. • There is nothing automatic that gives a pointer a valid pointee.
  • 7. Bad Pointers IT IS NOT NULL!
  • 8. Bad Pointers – Faster?! • Most languages make it easy to omit this important step. • The run-time checks are also a reason why such languages always run at least a little slower than a compiled language like C or C++!
  • 9.
  • 10.
  • 11.
  • 12. Bad Pointers - Example void BadPointer() { int* p; // allocate the pointer, but not the pointee *p = 42; // this dereference is a serious runtime error }
  • 13. Pointer Rules Summary • A pointer stores a reference to its pointee. The pointee, in turn, stores something useful. • The dereference operation on a pointer accesses its pointee. A pointer may only be dereferenced after it has been assigned to refer to a pointee. Most pointer bugs involve violating this one rule. • Allocating a pointer does not automatically assign it to refer to a pointee. Assigning the pointer to refer to a specific pointee is a separate operation which is easy to forget. • Assignment between two pointers makes them refer to the same pointee which introduces sharing.
  • 14. Large Locals Example void X() { int a = 1; int b = 2; // T1 Y(a); // T3 Y(b); // T5 } void Y(int p) { int q; q = p + 2; // T2 (first time through) // T4 (second time through) }
  • 16. A bit harder - Bill Gates By Value void B(int worth) { worth = worth + 1; // T2 } void A() { int netWorth; netWorth = 55; // T1 B(netWorth); // T3 -- B() did not change netWorth }
  • 17. A bit harder - Bill Gates By Value void B(int worth) { worth = worth + 1; // T2 } void A() { int netWorth; netWorth = 55; // T1 B(netWorth); // T3 -- B() did not change netWorth }
  • 18. A bit harder - Bill Gates By Reference void B(int &worth) { worth = worth + 1; // T2 } void A() { int netWorth; netWorth = 55; // T1 B(netWorth); // T3 -- B() did not change netWorth }
  • 19. A bit harder - Bill Gates By Reference void B(int *worth) { *worth = *worth + 1; // T2 } void A() { int netWorth; netWorth = 55; // T1 B(&netWorth); // T3 -- B() did not change netWorth }
  • 20.
  • 21.
  • 23. Heap! • "Heap" memory, also known as "dynamic" memory. • an alternative to local stack Memory.
  • 24. Facts • Local memory is quite automatic — it is allocated automatically on function call and it is deallocated automatically when a function exits. • Heap Lifetime – Because the programmer now controls exactly when memory is allocated and deallocated, it is possible to build a data structure in memory, and return that data structure to the caller. This was never possible with local memory which was automatically deallocated when the function exited.
  • 25. Heap - Allocation • Allocate 3 GIF images in the heap each of which takes 1024 bytes of memory.
  • 26. Heap - Deallocation • Deallocating Gif2 image
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35. both values and the variables are allocated memory. However, each assignment copies into the variable’s block, not the contents of the value block, but instead its address
  • 36. both values and the variables are allocated memory. However, each assignment copies into the variable’s block, not the contents of the value block, but instead its address
  • 37. null.toString(); • we get a NullPointerException (Java) • we can determine whether the value of a pointer variable is null or not, and hence, whether we can access its member.
  • 38. • Multiple pointers sharing a value
  • 39. Point p1 = new ACartesianPoint(50, 50); Point p2 = p1; p1.setX(100); System.out.println(p2.getX()); • When p1 is assigned to p2, the pointer stored in p1 is copied into p2, not the object itself. Both variables share the same object, and thus, the code will print 100 and not 50, as you might expect.
  • 40. Object Oriented Memory Management (Java and C++)
  • 41. Foreknowledge • A program address space: – Code area – Heap (Dynamic Memory Area) – Execution Stack
  • 42. Foreknowledge • Code area – where code to be executed is stored • Heap – store variables and objects allocated dynamically – accessed with no restrictions • Execution Stack – perform computation – store local variables – perform function call management
  • 43. accessed with a LIFO policy (Last In First Out)
  • 44. C++ Specific • C++ has several other memory areas • C++ the entire code is loaded into code area, and neglect dynamic loading.
  • 45. Activation Record (AR) void f(){ g(); } void g(){ h(); } void h(){ k(); }
  • 46. Activation Record (AR) void f(){ g(); } void g(){ h(); } void h(){ k(); }
  • 48. Scope Activation Record (SAR) is put every time a new block is encountered
  • 49. Scope Activation Record (SAR) • Contains: – Local variables (declared inside the block) – The Static Link SL (a.k.a SAR link) a pointer to the SAR of the immediate enclosing block; used to acce ss local variables of outer blocks from the current block.
  • 51. References and Pointers conceptually the SAME
  • 52. Classes and Objects Objects are instances of classes
  • 53. Classes and Objects Objects are instances of classes (Objects are classes in action)
  • 54. C++ again • In C++ classes are truly user defined ty pes. Objects are treated as any other variable and are allocated: – On the stack, as regular local variables – On the heap, like in Java
  • 55. Java example int[] hello = new int[5]; // reference hello is on stack, the object is on the // heap. hello[0] = 2; // Java puts this value directly in same slot and doesn't // create a wrapping object. From: http://stackoverflow.com/questions/10820787/how-does-java-treat-primitive-type-arrays
  • 56. Java: Why are wrapper classes needed? http://stackoverflow.com/questions/2134798/java-why-are-wrapper-classes-needed
  • 57. Java example public class CoffeeMaker { public CoffeeMaker(){} } .. .. CoffeeMaker aCoffeeMaker; aCoffeeMaker = new CoffeeMaker(); int sugar = 4; Integer sugarObject = new Integer(3);
  • 58. Java example public class CoffeeMaker { public CoffeeMaker(){} } .. .. CoffeeMaker aCoffeeMaker; aCoffeeMaker = new CoffeeMaker(); int sugar = 4; Integer sugarObject = new Integer(3);
  • 59. Java example • Java objects can be accessed just through reference variables, that hold the address of objects in heap.
  • 60. C++ example class CoffeeMaker { public: CoffeeMaker(); virtual ~CoffeeMaker(); }; // .. CoffeeMaker aCoffeeMaker; CoffeeMaker *aPtrCoffeeMaker = new CoffeeMaker(); CoffeeMaker &aRefCoffeeMaker = aCoffeeMaker; aRefCoffeeMaker = *aPtrCoffeeMaker; // dangerous! int sugar = 4; int *ptrSuger = new int; int &aRefSugar = sugar;
  • 62. Stack and Heap comparison
  • 63. Issues for objects in memory (Java) • Objects with no references pointing to them are considered eligible for automatic garbage collection by the system, which runs periodically and performs the real destruction of the objects. • GC is not directly under control of the programmer.
  • 64. Issues for objects in memory (C++) • After an object has been created on the heap (with the new directive) it survives until someone destroys it explicitly using the delete directive. • This could lead to memory leaks – if the programmer forgets to delete objects no longer needed, they remain on the heap as wasted space
  • 65. Methods (Java) public class CoffeeMaker { public void prepareCoffee() {} public void prepareCoffeeSweet(int sugarAm){} void main(...) { CoffeeMaker aCoffeeMaker; aCoffeeMaker = new CoffeeMaker(); aCoffeeMaker.prepareCoffee(); } }
  • 66. Methods (Java) public class CoffeeMaker { public void prepareCoffee() {} public void prepareCoffeeSweet(int sugarAm){} void main(...) { CoffeeMaker aCoffeeMaker; aCoffeeMaker = new CoffeeMaker(); aCoffeeMaker.prepareCoffee(); } }
  • 67. Methods (C++) class CoffeeMaker { public: void prepareCoffee() {} void prepareCoffeeSweet(int sugarAm){} void main(...) { CoffeeMaker *aPtrCoffeeMaker; aPtrCoffeeMaker = new CoffeeMaker; aPtrCoffeeMaker-> prepareCoffee(); } }
  • 68. Methods (C++) class CoffeeMaker { public: void prepareCoffee() {} void prepareCoffeeSweet(int sugarAm){} void main(...) { CoffeeMaker *aPtrCoffeeMaker; aPtrCoffeeMaker = new CoffeeMaker; aPtrCoffeeMaker-> prepareCoffee(); } }
  • 70. Read! • http://www.simple-talk.com/dotnet/.net-framework/understanding- garbage-collection-in-.net/ • http://en.wikibooks.org/wiki/C_Programming/Memory_management • (.pdf) Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework