Objective C/C++  Работа с памятью безиспользования Instruments
Memory and resource managementLOCAL OBJECTS
C• System language• Portable assembler
C• Memory management - C example  static bool check_memory()  {  !   Something * a = (Something *)malloc( sizeof(Something...
C• Resource management - C example  static bool check_file(const char * name)  {  !   FILE * fs = fopen(name, "rb");  !   ...
C• Resource management - C example  static bool check_file(const char * name)  {  !   FILE * fs = fopen(name, "rb");  !   ...
Java• Memory management example     static public boolean check_memory() 	   { 	   	   Something a = new Something(); 	   ...
Java• Resource management example     static public boolean check_file(String name) throws Exception 	   { 	   	   FileInp...
Java• Resource management example     static public boolean check_file(String name) throws Exception 	   { 	   	   FileInp...
Java• Resource management - with finally 	   static public boolean check_file2(String name) throws Exception 	   { 	   	   ...
Java• Resource management - with catch 	   static public boolean check_file3(String name) throws Exception 	   { 	   	    ...
C#• Memory management example     static public bool check_memory() 	   { 	   	   Something a = new Something(); 	   	   a...
C#• Resource management example     static public bool check_file(String name) 	   { 	   	   using( FileInputStream fs = n...
C++• System language• Life without garbage collector?• Unique semantic!
C++• Memory management - what C  developer thinks?• If I know C I already know C++!   static bool check_memory()   {   !  ...
C++• Memory management - what C  developer thinks?• If I know C I already know C++!   static bool check_memory()   {   !  ...
C++•   Are there exceptions in C++?•   Are they good or evil? Good!•   If I do not use them?•   You are allowed not to thr...
C++• Memory management example  static bool check_memory()  {  !   std::auto_ptr<Something> a( new Something );  !   a->do...
C++• Resource management example  static bool check_file(const std::string & name)  {  !   liba::FileInputStream fs(name);...
C++• Resource management example  static bool check_file(const std::string & name)  {  !   std::auto_ptr<liba::FileInputSt...
C++• Delete is for implementing libraries! { 	   std::auto_ptr<Something> a( new Something(...) ); 	 	   if( ... ) 	   	  ...
Objective-C• Memory management - what C  developer thinks?• If I know C I already know Objective-C!   -(bool)check_memory ...
Objective-C• Memory management - what C  developer thinks?• If I know C I already know Objective-C!   static bool check_me...
Objective-C• Are there exceptions in Objective-C?• Are they good or evil? Absolutely good!   -(void)parse_object:(NSDictio...
Objective-C• Memory management example -(bool)check_memory { !   Something * a = [[[Something alloc] init] autorelease]; !...
Objective-C• Memory management example  -(bool)check_memory  {  !   Something * a = [[[Something alloc] init] autorelease]...
Memory and resource managementLONG-LIVED OBJECTS
ApproachesGarbage collector   Ownership graph
Approaches• It takes lots of CPU time to untangle this!
Approaches• You must prove the graph is acyclic!
Approaches• What is more scary than memory leak?
Approaches• What is more scary than memory leak?• Dangling pointer!
Objective-C• Retaining  @interface Something : NSObject {  !   Anything * a;  }  @end  @implementation Something  -(void)d...
Objective-C• Retaining  @interface Something : NSObject {  !   Anything * a;  }  @property(nonatomic, retain) Anything * a...
Objective-C• Subtle differences  !   self.a = new_a; // Call property  !   self->a = new_a; // Use variable  !   a = new_a...
Objective-C• Subtle differences  @interface Something : NSObject {  !   Anything * a_zlo_hren;  }  @property(nonatomic, re...
Objective-C• 4 lines to free the memory? Too much.     Anything * a_zlo_hren; @property(nonatomic, retain) Anything * a; @...
Objective-C++• Objective C is also C++  @interface Something : NSObject {  !   NSPtr<Anything> a;  }  @end  @implementatio...
Objective-C++• Retain cycles  @interface Something : NSObject {  !   Anything * a;  }  @property(nonatomic, retain) Anythi...
Objective-C++• Retain cycles  @interface Something : NSObject {  !   Anything * a;  }  @property(nonatomic, retain) Anythi...
Objective-C++• Retain cycles  @interface Something : NSObject {  !   Anything * a;  }  @property(nonatomic, retain) Anythi...
Retain cycles• Can compiler find them?• Can runtime find them?• Can tools find them?• Is there a simple approach to avoid  th...
Retain cycles• Can compiler find them?Yes, soon (experimental languages).• Can runtime find them?• Can tools find them?• Is t...
Retain cycles• Can compiler find them?Yes, soon (experimental languages).• Can runtime find them?Yes, Garbage Collector.• Ca...
Retain cycles• Can compiler find them?Yes, soon (experimental languages).• Can runtime find them?Yes, Garbage Collector.• Ca...
Retain cycles• Can compiler find them?Yes, soon (experimental languages).• Can runtime find them?Yes, Garbage Collector.• Ca...
Objective-C• Containers always retain  @interface Something : NSObject {  !   NSMutableArray * a;  }  @property(nonatomic,...
Objective-C• If we do not want to retain?  @interface Something : NSObject {  !   NSMutableArray * a;  }  @property(nonato...
Objective-C• What if we retain by accident?  @interface Something : NSObject {  !   NSMutableArray * a;  }  @property(nona...
Objective-C• Containers are untyped @interface Something : NSObject { !   NSMutableArray * a; // Of Anything } @property(n...
Objective-C• Untyped containers are hard to prove  @interface Something : NSObject {  !   NSMutableArray * a; // Of Anythi...
Objective-C++• We can use great STL containers  @interface Something : NSObject {  !   std::vector<Anything *> a;  }  @end...
Objective-C++• Retain strategy is independent  @interface Something : NSObject {  !   std::vector< NSPtr<Anything> > a;  }...
Objective-C++• Integration is almost flawless!• Apple teams actually use C++ and STL @interface Something : NSObject { !   ...
Success• alloc-init-autorelease idiom• NSPtr or @property(retain) to manage  retain/release• Use text editor to eliminate ...
What we forgot?• Active objects (timers, http requests)• Parallel execution (NSOperation)
What we forgot?• Active objects (timers, http requests)• Parallel execution (NSOperation)         Do not worry!        Thi...
Q&A                  Q&AGrigory Buteykohrissan@mail.ruwww.dataart.com
Upcoming SlideShare
Loading in …5
×

Objective-c memory

2,916 views

Published on

Published in: Technology, Health & Medicine
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,916
On SlideShare
0
From Embeds
0
Number of Embeds
1,485
Actions
Shares
0
Downloads
37
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Objective-c memory

  1. 1. Objective C/C++ Работа с памятью безиспользования Instruments
  2. 2. Memory and resource managementLOCAL OBJECTS
  3. 3. C• System language• Portable assembler
  4. 4. C• Memory management - C example static bool check_memory() { ! Something * a = (Something *)malloc( sizeof(Something) ); ! if( !a ) ! ! return false; ! do_something(a); ! if( some_condition(a) ) ! { ! ! free(a); ! ! return true; ! } ! // Lots of code ! free(a); ! return false; }
  5. 5. C• Resource management - C example static bool check_file(const char * name) { ! FILE * fs = fopen(name, "rb"); ! if( !fs ) ! ! return false; ! int first = fgetc(fs); ! if( first == 32 ) ! { ! ! fclose(fs); ! ! return true; ! } ! // Lots of code ! fclose(fs); ! return false; }
  6. 6. C• Resource management - C example static bool check_file(const char * name) { ! FILE * fs = fopen(name, "rb"); ! if( !fs ) ! ! return false; ! int first = fgetc(fs); ! if( first == 32 ) ! { ! ! fclose(fs); ! ! return true; ! } ! // Lots of code ! fclose(fs); ! return false; }
  7. 7. Java• Memory management example static public boolean check_memory() { Something a = new Something(); a.do_something(); if( a.some_condition() ) return true; // Lots of code return false; }
  8. 8. Java• Resource management example static public boolean check_file(String name) throws Exception { FileInputStream fs = new FileInputStream(name); int first = fs.read(); if( first == 32 ) return true; // Lots of code return false; }
  9. 9. Java• Resource management example static public boolean check_file(String name) throws Exception { FileInputStream fs = new FileInputStream(name); int first = fs.read(); if( first == 32 ) return true; // Lots of code return false; } static public void delete_if_bad(String name) throws Exception { if( !check_file(name) ) new java.io.File(name).delete(); }
  10. 10. Java• Resource management - with finally static public boolean check_file2(String name) throws Exception { FileInputStream fs = null; try { fs = new FileInputStream(name); int first = fs.read(); if( first == 32 ) return true; // Lots of code return false; } finally{ if( fs != null ) fs.close(); } }
  11. 11. Java• Resource management - with catch static public boolean check_file3(String name) throws Exception { FileInputStream fs = null; try { fs = new FileInputStream(name); int first = fs.read(); if( first == 32 ) return true; // Lots of code } catch(Exception e) {} try { if( fs != null ) fs.close(); } catch(Exception e) {} return false; }
  12. 12. C#• Memory management example static public bool check_memory() { Something a = new Something(); a.do_something(); if( a.some_condition() ) return true; // Lots of code return false; }
  13. 13. C#• Resource management example static public bool check_file(String name) { using( FileInputStream fs = new FileInputStream(name) ) { int first = fs.read(); if( first == 32 ) return true; // Lots of code } return false; }
  14. 14. C++• System language• Life without garbage collector?• Unique semantic!
  15. 15. C++• Memory management - what C developer thinks?• If I know C I already know C++! static bool check_memory() { ! Something * a = new Something; ! if( !a ) ! ! return false; ! a->do_something(); ! if( a->some_condition() ) ! { ! ! delete a; ! ! return true; ! } ! // Lots of code ! delete a; ! return false; }
  16. 16. C++• Memory management - what C developer thinks?• If I know C I already know C++! static bool check_memory() { ! Something * a = (Something *)malloc( sizeof(Something) ); ! if( !a ) ! ! return false; ! do_something(a); ! if( some_condition(a) ) ! { ! ! free(a); ! ! return true; ! } ! // Lots of code ! free(a); ! return false; }
  17. 17. C++• Are there exceptions in C++?• Are they good or evil? Good!• If I do not use them?• You are allowed not to throw• But good C++ design always uses exceptions, so you better be prepared
  18. 18. C++• Memory management example static bool check_memory() { ! std::auto_ptr<Something> a( new Something ); ! a->do_something(); ! if( a->some_condition() ) ! ! return true; ! // Lots of code ! return false; }
  19. 19. C++• Resource management example static bool check_file(const std::string & name) { ! liba::FileInputStream fs(name); ! int first = fs.read(); ! if( first == 32 ) ! ! return true; ! // Lots of code ! return false; }
  20. 20. C++• Resource management example static bool check_file(const std::string & name) { ! std::auto_ptr<liba::FileInputStream> fs( liba::create_fis(name) ); ! int first = fs->read(); ! if( first == 32 ) ! ! return true; ! // Lots of code ! return false; }
  21. 21. C++• Delete is for implementing libraries! { std::auto_ptr<Something> a( new Something(...) ); if( ... ) return; }• No difference between memory and other resource types
  22. 22. Objective-C• Memory management - what C developer thinks?• If I know C I already know Objective-C! -(bool)check_memory { ! Something * a = [[Something alloc] init]; ! if( !a ) ! ! return false; ! [a do_something]; ! if( [a some_condition] ) ! { ! ! [a release]; ! ! return true; ! } ! // Lots of code ! [a release]; ! return false; }
  23. 23. Objective-C• Memory management - what C developer thinks?• If I know C I already know Objective-C! static bool check_memory() { ! Something * a = (Something *)malloc( sizeof(Something) ); ! if( !a ) ! ! return false; ! do_something(a); ! if( some_condition(a) ) ! { ! ! free(a); ! ! return true; ! } ! // Lots of code ! free(a); ! return false; }
  24. 24. Objective-C• Are there exceptions in Objective-C?• Are they good or evil? Absolutely good! -(void)parse_object:(NSDictionary *)dic { ! // Lots of code ! int val = [[[dic objectForKey:@"users"] objectAtIndex:0] intValue]; ! // Lots of code } -(void)parse_object:(NSDictionary *)dic { ! // Lots of code ! NSArray * arr = [dic objectForKey:@"users"]; ! if( ![arr isKindOfClass:[NSArray class]] ) ! ! return; // But we must tell about error... ! NSNumber * num = [arr objectAtIndex:0]; ! if( ![num isKindOfClass:[NSNumber class]] ) ! ! return; // But we must tell about error... ! int val = [num intValue]; ! // Lots of code }
  25. 25. Objective-C• Memory management example -(bool)check_memory { ! Something * a = [[[Something alloc] init] autorelease]; ! [a do_something]; ! if( [a some_condition] ) ! ! return true; ! // Lots of code ! return false; }
  26. 26. Objective-C• Memory management example -(bool)check_memory { ! Something * a = [[[Something alloc] init] autorelease]; ! [a do_something]; ! if( [a some_condition] ) ! ! return true; ! // Lots of code ! return false; }• Afraid of autorelease?• Just start using it!• It is widely used in Cocoa
  27. 27. Memory and resource managementLONG-LIVED OBJECTS
  28. 28. ApproachesGarbage collector Ownership graph
  29. 29. Approaches• It takes lots of CPU time to untangle this!
  30. 30. Approaches• You must prove the graph is acyclic!
  31. 31. Approaches• What is more scary than memory leak?
  32. 32. Approaches• What is more scary than memory leak?• Dangling pointer!
  33. 33. Objective-C• Retaining @interface Something : NSObject { ! Anything * a; } @end @implementation Something -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! [a release]; // [a autorelease]; ! a = [new_a retain]; } -(void)dealloc { ! [a release]; ! [super dealloc]; } @end
  34. 34. Objective-C• Retaining @interface Something : NSObject { ! Anything * a; } @property(nonatomic, retain) Anything * a; @end @implementation Something @synthesize a; -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! self.a = new_a; } -(void)dealloc { ! self.a = 0; ! [super dealloc]; } @end
  35. 35. Objective-C• Subtle differences ! self.a = new_a; // Call property ! self->a = new_a; // Use variable ! a = new_a; // ???
  36. 36. Objective-C• Subtle differences @interface Something : NSObject { ! Anything * a_zlo_hren; } @property(nonatomic, retain) Anything * a; @end @implementation Something @synthesize a = a_zlo_hren; -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! self.a = new_a; // Call property ! self->a = new_a; // Use variable ! a = new_a; // ??? }
  37. 37. Objective-C• 4 lines to free the memory? Too much. Anything * a_zlo_hren; @property(nonatomic, retain) Anything * a; @synthesize a = a_zlo_hren; ! self.a = 0; // In dealloc
  38. 38. Objective-C++• Objective C is also C++ @interface Something : NSObject { ! NSPtr<Anything> a; } @end @implementation Something -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! a = new_a; } @end• 4 lines go down to 1, good!
  39. 39. Objective-C++• Retain cycles @interface Something : NSObject { ! Anything * a; } @property(nonatomic, retain) Anything * a; @end @interface Anything : NSObject { ! Something * s; } @property(nonatomic, retain) Something * s; @end
  40. 40. Objective-C++• Retain cycles @interface Something : NSObject { ! Anything * a; } @property(nonatomic, retain) Anything * a; @end @interface Anything : NSObject { ! Something * s; } @property(nonatomic, retain) Something * s; @end
  41. 41. Objective-C++• Retain cycles @interface Something : NSObject { ! Anything * a; } @property(nonatomic, retain) Anything * a; @end @interface Anything : NSObject { ! Something * s; } @end
  42. 42. Retain cycles• Can compiler find them?• Can runtime find them?• Can tools find them?• Is there a simple approach to avoid them?
  43. 43. Retain cycles• Can compiler find them?Yes, soon (experimental languages).• Can runtime find them?• Can tools find them?• Is there a simple approach to avoid them?
  44. 44. Retain cycles• Can compiler find them?Yes, soon (experimental languages).• Can runtime find them?Yes, Garbage Collector.• Can tools find them?• Is there a simple approach to avoid them?
  45. 45. Retain cycles• Can compiler find them?Yes, soon (experimental languages).• Can runtime find them?Yes, Garbage Collector.• Can tools find them?Yes, if included in test cases.• Is there a simple approach to avoid them?
  46. 46. Retain cycles• Can compiler find them?Yes, soon (experimental languages).• Can runtime find them?Yes, Garbage Collector.• Can tools find them?Yes, if included in test cases.• Is there a simple approach to avoid them?Yes, analyze architecture.
  47. 47. Objective-C• Containers always retain @interface Something : NSObject { ! NSMutableArray * a; } @property(nonatomic, retain) NSMutableArray * a; @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! Anything * new_a2 = [[[Anything alloc] init] autorelease]; ! [a addObject:new_a]; ! [a addObject:new_a2]; }
  48. 48. Objective-C• If we do not want to retain? @interface Something : NSObject { ! NSMutableArray * a; } @property(nonatomic, retain) NSMutableArray * a; @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! Anything * new_a2 = [[[Anything alloc] init] autorelease]; ! [a addObject:[NSValue valueWithNonretainedObject:new_a]]; ! [a addObject:[NSValue valueWithNonretainedObject:new_a2]]; } -(void)use_something { ! Anything * aa = [[a objectAtIndex:0] nonretainedObjectValue]; }
  49. 49. Objective-C• What if we retain by accident? @interface Something : NSObject { ! NSMutableArray * a; } @property(nonatomic, retain) NSMutableArray * a; @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! Anything * new_a2 = [[[Anything alloc] init] autorelease]; ! [a addObject:new_a]; // Someone forgot ! [a addObject:new_a2]; // Someone forgot }
  50. 50. Objective-C• Containers are untyped @interface Something : NSObject { ! NSMutableArray * a; // Of Anything } @property(nonatomic, retain) NSMutableArray * a; // Of Anything @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! Anything * new_a2 = [[[Anything alloc] init] autorelease]; ! [a addObject:new_a]; ! [a addObject:new_a2]; }
  51. 51. Objective-C• Untyped containers are hard to prove @interface Something : NSObject { ! NSMutableArray * a; // Of Anything } @property(nonatomic, retain) NSMutableArray * a; // Of Anything @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! NSString * str = @"Hi"; ! [a addObject:new_a]; ! [a addObject:str]; }
  52. 52. Objective-C++• We can use great STL containers @interface Something : NSObject { ! std::vector<Anything *> a; } @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! NSString * str = @"Hi"; ! a.push_back( new_a ); ! a.push_back( str ); }
  53. 53. Objective-C++• Retain strategy is independent @interface Something : NSObject { ! std::vector< NSPtr<Anything> > a; } @end -(void)do_something { ! Anything * new_a = [[[Anything alloc] init] autorelease]; ! NSString * str = @"Hi"; ! a.push_back( new_a ); ! a.push_back( str ); }
  54. 54. Objective-C++• Integration is almost flawless!• Apple teams actually use C++ and STL @interface Something : NSObject { ! std::vector< id<UIActionSheetDelegate> > a; } @end -(void)do_something { ! std::for_each(a.begin(), a.end(), ^(id<UIActionSheetDelegate> x) { ! ! [x actionSheetCancel:nil]; ! }); }
  55. 55. Success• alloc-init-autorelease idiom• NSPtr or @property(retain) to manage retain/release• Use text editor to eliminate all retain, release• Architecture with no cycles• Typed containers (STL), so the compiler can actually prove most of your architecture
  56. 56. What we forgot?• Active objects (timers, http requests)• Parallel execution (NSOperation)
  57. 57. What we forgot?• Active objects (timers, http requests)• Parallel execution (NSOperation) Do not worry! This is also easy!
  58. 58. Q&A Q&AGrigory Buteykohrissan@mail.ruwww.dataart.com

×