使用XCode Clang(静态分析器)发现内存泄露
XCode中引入了静态分析器,用于发现普通编译错误以外的错误
选择Build->Build and Analyze
请看下面这段代码
#import <Foundation/FOundation.h>
int main(int agrc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDate *date = [[NSDate alloc] init];
NSLog(@"The time is: %@", date);
[pool drain];
return 0;
}
int main(int agrc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDate *date = [[NSDate alloc] init];
NSLog(@"The time is: %@", date);
[pool drain];
return 0;
}
上面这段代码中, date对象在创建后没有被释放
所以, 我们应该加上[date release]
正确的代码
#import <Foundation/FOundation.h>
int main(int agrc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDate *date = [[NSDate alloc] init];
NSLog(@"The time is: %@", date);
[date release];
[pool drain];
return 0;
}
int main(int agrc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDate *date = [[NSDate alloc] init];
NSLog(@"The time is: %@", date);
[date release];
[pool drain];
return 0;
}
技术改变世界