leaks tool doesn't report memory leak on os x

醉酒当歌 提交于 2019-12-24 11:25:38

问题


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;
}

I learned that leaks refreshes itself every 10 seconds (not sure if this is true, but I set the interval to 20 seconds).

This should produce leaks because it is not in auto release pool and also I compiled with -fno-objc-arc for "safety".

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?


回答1:


NSString *string = [[NSString alloc] init];

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.

The same behaviour can be observed with other immutable classes (NSArray, NSDictionary).

If you replace your line with

NSMutableString *string = [[NSMutableString alloc] init];

then you will see a memory leak.




回答2:


  1. If you use ARC there's no leak.
  2. The empty string ([[NSString alloc] init]) is most definitely a shared/reused instance. The system has to keep a reference to the shared instance, so leaks would (correctly) not report it.

A better test would be to use a custom object. Then you can be sure that there is no magic involved.

#if __has_feature(objc_arc)
#error This leaks test only works when ARC is off
#endif

@interface Orphan : NSObject @end
@implementation Orphan @end


// in main, create an object without keeping a reference to it:
[Orphan new];


来源:https://stackoverflow.com/questions/18652370/leaks-tool-doesnt-report-memory-leak-on-os-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!