2010-04-01 3 views
0

지난 몇 시간 동안 코드에서 메모리 누수를 찾으려고했습니다. 여기입니다 : 내가 코코아 메모리 관리의 몇 가지 기본 규칙을 따르려고했는데, 어떻게 든 여전히 누수가있을 것 같습니다코드에서 누출을 찾을 수 없습니다.

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

expression = [expression stringByTrimmingCharactersInSet: 
       [NSCharacterSet whitespaceAndNewlineCharacterSet]]; // expression is an NSString object. 

NSArray *arguments = [NSArray arrayWithObjects:expression, [@"~/Desktop/file.txt" stringByExpandingTildeInPath], @"-n", @"--line-number", nil]; 
NSPipe *outPipe = [[NSPipe alloc] init]; 

NSTask *task = [[NSTask alloc] init]; 
[task setLaunchPath:@"/usr/bin/grep"]; 
[task setArguments:arguments]; 
[task setStandardOutput:outPipe]; 
[outPipe release]; 

[task launch]; 

NSData *data = [[outPipe fileHandleForReading] readDataToEndOfFile]; 

[task waitUntilExit]; 
[task release]; 

NSString *string = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding]; 
string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""]; 

int linesNum = 0; 

NSMutableArray *possibleMatches = [[NSMutableArray alloc] init]; 

if ([string length] > 0) { 

    NSArray *lines = [string componentsSeparatedByString:@"\n"]; 
    linesNum = [lines count]; 

    for (int i = 0; i < [lines count]; i++) { 

     NSString *currentLine = [lines objectAtIndex:i]; 
     NSArray *values = [currentLine componentsSeparatedByString:@"\t"]; 

     if ([values count] == 20) 
      [possibleMatches addObject:currentLine]; 
    } 
} 
[string release]; 
[pool release]; 

return [possibleMatches autorelease]; 

, 나는 새는 배열 믿습니다. 가능한 경우 큰 눈에 띄게됩니다. 큰 파일을 "~/Desktop/file.txt"로 사용하고 grep-ing 할 때 많은 결과를 나타내는 표현식으로 코드를 시도 할 수 있습니다.

내가 뭘 만들고있어?

도움 주셔서 감사합니다.

- Ry가

편집 : 난 그냥 내 코드에서 누수를 찾기 위해 연타하다 정적 분석기를 사용하지만 아무것도 발견하지 않습니다. 그것은 단지 죽은 초기화를 찾았지만 그 내 누출에 대해 책임을지지 않습니다 ... 여기

+0

따로 : 인덱스가 필요하지 않을 때마다 빠른 열거 형을 사용해야합니다 ('for (NSString * currentLine in lines)'). 코드가 깨끗하고 타이핑이 적으며 속도가 빠릅니다. –

답변

3

:

NSString *string = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding]; 
string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""]; 

당신은 해제하거나 원래 문자열을 autoreleasing없이 string 개체 포인터를 덮어 쓰는 것입니다. 대신에있어서의 단부를 이탈 string, 수행

NSString *string = [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding] autorelease]; 
string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""]; 
+0

고마워,하지만 아직 누수가있다. – ryyst

+0

'누출량 '은 무엇을 말합니까? – Wevah

+0

또한, 'MallocStackLogging' 환경 변수를 설정하면 누수가 정확히 어디에 할당되어 있는지 추적 할 수 있습니다. – Wevah

0

용액 개연성 경로 인스트루먼트 누수 템플릿을 사용하는 것이다. 검사 범위를이 코드 바로 앞에서 시작하도록 설정하면이 코드가 반환 된 후에 어떤 할당이 아직 살아 있는지 보면서 누출 된 것을 확인한 다음 누수의 포인터 내역과 해당 스택 추적을 정확하게 볼 수 있습니다 어떻게 된 거예요.