gpt4 book ai didi

cocoa - 在我的代码中找不到泄漏

转载 作者:行者123 更新时间:2023-12-03 17:36:57 25 4
gpt4 key购买 nike

过去几个小时我一直在尝试查找代码中的内存泄漏。这是:

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

我尝试遵循Cocoa内存管理的一些基本规则,但不知何故似乎仍然存在泄漏,我相信这是一个数组泄漏。如果 possibleMatches 很大,就会很明显。您可以通过使用任何大文件作为“~/Desktop/file.txt”以及作为 grep 时产生许多结果的表达式来尝试该代码。

我犯了什么错误?

感谢您的帮助!

-- 瑞

编辑:我刚刚使用 Clang 静态分析器来查找代码中的泄漏,但它没有找到任何泄漏。它只找到死初始化,但这些不能对我的泄漏负责......

最佳答案

这里:

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

您正在覆盖string对象指针,而不释放或自动释放原始字符串。不要在方法末尾释放 string,而是执行以下操作:

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

关于cocoa - 在我的代码中找不到泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2563134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com