泄漏工具不会报告OS X上的内存泄漏 [英] leaks tool doesn't report memory leak on os x
问题描述
我正在尝试从命令行学习如何使用泄漏工具,这是我的代码,应在NSString
上产生泄漏:
I am trying to learn how to use leaks tool from the command line, here is my code that should produce a leak on NSString
:
#import <Foundation/Foundation.h>
#import <unistd.h>
int main(int argc, const char *argv[])
{
NSString *string = [[NSString alloc] init];
pid_t pid = getpid();
NSLog(@"pid: %d", pid);
string = nil;
[NSThread sleepForTimeInterval:20];
return 0;
}
我了解到泄漏会每10秒刷新一次(不确定这是否成立,但是我将间隔设置为20秒).
I learned that leaks refreshes itself every 10 seconds (not sure if this is true, but I set the interval to 20 seconds).
这应该会产生泄漏,因为它不在自动发布池中,并且我还使用-fno-objc-arc
进行了编译以确保安全".
This should produce leaks because it is not in auto release pool and also I compiled with -fno-objc-arc
for "safety".
我尝试多次运行泄漏[pid]
,但没有泄漏报告.我在这里做错了什么?
另外,我是命令行迷,我真的很想能够使用类似于valgrind的东西,它不非常支持os x 10.8.烦人的是,为了使用泄漏工具,我不得不在代码中入睡.
I tried to run leaks [pid]
multiple times with no leaks reported. What am I doing wrong here?
Also, I am a command line fan and really want to be able to use something similar to valgrind, which doesn't support os x 10.8 very well. It is annoying that I have to put sleep in my code in order to use leaks tool.
任何人都可以在这里点亮一些灯光吗?
Can anyone please shine some lights here?
推荐答案
NSString *string = [[NSString alloc] init];
返回一个空字符串的共享实例(并且多次调用返回相同的实例). Foundation框架保留对此共享实例的引用,因此 没有内存泄漏.
returns a shared instance of an empty string (and multiple calls return the same instance). The Foundation framework keeps a reference to this shared instance, therefore there is no memory leak.
在其他不可变类(NSArray
,NSDictionary
)上也可以观察到相同的行为.
The same behaviour can be observed with other immutable classes (NSArray
, NSDictionary
).
如果您将行替换为
NSMutableString *string = [[NSMutableString alloc] init];
然后您将看到内存泄漏.
then you will see a memory leak.
这篇关于泄漏工具不会报告OS X上的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!