11 September 2011

What if you forgot to deallocate reserved memory in your objective-c (c/c++) programs?

The worst thing ever that I usually do is to forget to deallocates memory for objects I create when working with non-garbage collector languages (like C/C++/Objective C) So, That If I didn't de-allocate the memory .. what in that?? Actually it is a disaster ... Watch this example:
  1. #import <Foundation/Foundation.h>
  2. 
  3. int main(void)
  4. {
  5.     long long i;
  6.     for (i=0; i < 100000000000000; i++)
  7.     {
  8.         NSString* string = [[NSString alloc] initWithString :@"string"];
  9.         //[string release];
 10.     }
 11. 
 12.     [NSThread sleepForTimeInterval: 5];
 13.     
 14.     return 0;
 15. }
Then compile and run with GNUstep, the memory used by the program reaches 2 GB (I've 4 GB of RAM), and then the program terminates printing:
Virtual memory exhausted

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Remember, each time you enter a block of code (method for example) and allocate the miss to deallocate the memory you allocate will add this to the RAM and will not remove..finally you may find your program get crashed because it uses too much memory !
Post a Comment