Memory Management with Java and C++

1,780 views
1,544 views

Published on

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,780
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
57
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Memory Management with Java and C++

  1. 1. Understanding Memory Managementand Garbage Collection Java and C++ Mohammad Shaker FIT of Damascus - AI dept. MohammadShakerGtr@gmail.com Programming Languages
  2. 2. What Is A Pointer?
  3. 3. NULL Pointer
  4. 4. Pointer Assignment
  5. 5. Shallow and Deep Copying
  6. 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. 7. Bad Pointers IT IS NOT NULL!
  8. 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. 9. Bad Pointers - Examplevoid BadPointer() {int* p; // allocate the pointer, but not the pointee*p = 42; // this dereference is a serious runtime error}
  10. 10. 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.
  11. 11. Large Locals Examplevoid 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)}
  12. 12. Large Locals Example
  13. 13. A bit harder - Bill Gates By Valuevoid B(int worth) { worth = worth + 1; // T2}void A() { int netWorth; netWorth = 55; // T1 B(netWorth); // T3 -- B() did not change netWorth}
  14. 14. A bit harder - Bill Gates By Valuevoid B(int worth) { worth = worth + 1; // T2}void A() { int netWorth; netWorth = 55; // T1 B(netWorth); // T3 -- B() did not change netWorth}
  15. 15. A bit harder - Bill Gates By Referencevoid B(int &worth) { worth = worth + 1; // T2}void A() { int netWorth; netWorth = 55; // T1 B(netWorth); // T3 -- B() did not change netWorth}
  16. 16. A bit harder - Bill Gates By Referencevoid B(int *worth) { *worth = *worth + 1; // T2}void A() { int netWorth; netWorth = 55; // T1 B(&netWorth); // T3 -- B() did not change netWorth}
  17. 17. Heap Memory
  18. 18. Heap!• "Heap" memory, also known as "dynamic" memory.• an alternative to local stack Memory.
  19. 19. 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.
  20. 20. Heap - Allocation• Allocate 3 GIF images in the heap each of which takes 1024 bytes of memory.
  21. 21. Heap - Deallocation• Deallocating Gif2 image
  22. 22. Simple Heap Example
  23. 23. Simple Heap Example
  24. 24. Simple Heap Example
  25. 25. • 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
  26. 26. • 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
  27. 27. 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.
  28. 28. • Multiple pointers sharing a value
  29. 29. 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.
  30. 30. Object Oriented Memory Management (Java and C++)
  31. 31. Foreknowledge• A program address space: – Code area – Heap (Dynamic Memory Area) – Execution Stack
  32. 32. 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
  33. 33. accessed with a LIFO policy (Last In First Out)
  34. 34. C++ Specific• C++ has several other memory areas• C++ the entire code is loaded into code area, and neglect dynamic loading.
  35. 35. Activation Record (AR)void f(){ g();}void g(){ h();}void h(){ k();}
  36. 36. Activation Record (AR)void f(){ g();}void g(){ h();}void h(){ k();}
  37. 37. Abbreviations for AR•
  38. 38. Scope Activation Record (SAR) is put every time a new block is encountered
  39. 39. 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.
  40. 40. Scope Activation Record (SAR)
  41. 41. References and Pointers conceptually the SAME
  42. 42. Classes and ObjectsObjects are instances of classes
  43. 43. Classes and ObjectsObjects are instances of classes (Objects are classes in action)
  44. 44. 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
  45. 45. Java exampleint[] 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 doesnt// create a wrapping object.From: http://stackoverflow.com/questions/10820787/how-does-java-treat-primitive-type-arrays
  46. 46. Java: Why are wrapper classes needed? http://stackoverflow.com/questions/2134798/java-why-are-wrapper-classes-needed
  47. 47. Java examplepublic class CoffeeMaker { public CoffeeMaker(){}}....CoffeeMaker aCoffeeMaker;aCoffeeMaker = new CoffeeMaker();int sugar = 4;Integer sugarObject = new Integer(3);
  48. 48. Java examplepublic class CoffeeMaker { public CoffeeMaker(){}}....CoffeeMaker aCoffeeMaker;aCoffeeMaker = new CoffeeMaker();int sugar = 4;Integer sugarObject = new Integer(3);
  49. 49. Java example• Java objects can be accessed just through reference variables, that hold the address of objects in heap.
  50. 50. C++ exampleclass 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;
  51. 51. C++ example
  52. 52. Stack and Heap comparison
  53. 53. 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.
  54. 54. 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
  55. 55. Methods (Java)public class CoffeeMaker { public void prepareCoffee() {} public void prepareCoffeeSweet(int sugarAm){} void main(...) { CoffeeMaker aCoffeeMaker; aCoffeeMaker = new CoffeeMaker(); aCoffeeMaker.prepareCoffee(); }}
  56. 56. Methods (Java)public class CoffeeMaker { public void prepareCoffee() {} public void prepareCoffeeSweet(int sugarAm){} void main(...) { CoffeeMaker aCoffeeMaker; aCoffeeMaker = new CoffeeMaker(); aCoffeeMaker.prepareCoffee(); }}
  57. 57. Methods (C++)class CoffeeMaker { public: void prepareCoffee() {} void prepareCoffeeSweet(int sugarAm){} void main(...) { CoffeeMaker *aPtrCoffeeMaker; aPtrCoffeeMaker = new CoffeeMaker; aPtrCoffeeMaker-> prepareCoffee(); }}
  58. 58. Methods (C++)class CoffeeMaker { public: void prepareCoffee() {} void prepareCoffeeSweet(int sugarAm){} void main(...) { CoffeeMaker *aPtrCoffeeMaker; aPtrCoffeeMaker = new CoffeeMaker; aPtrCoffeeMaker-> prepareCoffee(); }}
  59. 59. UnderstandingGarbage Collection
  60. 60. 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
  61. 61. Dangerous Finalize()!
  62. 62. Keep goin’

×