写了一个简单的程序来填充我的驱动器上的所有空间。它有一个非常简单的逻辑:
好吧,我刚从头创建了一个新的Cocoa项目,并将代码放在applicationDidFinishLaunching
中。就是这样。
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
fm = [NSFileManager new];
unsigned long long size = 0;
unsigned long long sizeMax = 0;
NSString *path;
NSData *data;
NSFileHandle *myHandle;
for (long i = 0; ; ++i) {
if (i % 40L == 0) { // N = 40
sizeMax = [self currentMaxSize];
size = 0;
path = [NSString stringWithFormat:@"/Users/user/Desktop/loltest/lol_%f.txt", [NSDate timeIntervalSinceReferenceDate]];
[fm createFileAtPath:path contents:[NSData data] attributes:nil];
[myHandle closeFile];
myHandle = [NSFileHandle fileHandleForWritingAtPath:path];
}
[myHandle seekToEndOfFile];
data = [self randomData];
size += data.length;
[myHandle writeData:data];
data = nil;
if (size >= sizeMax) {
[myHandle closeFile];
break;
}
}
NSLog(@"OKAY");
}
- (unsigned long long)currentMaxSize
{
return [[fm attributesOfFileSystemForPath:@"/" error:nil][NSFileSystemFreeSize] unsignedLongLongValue];
}
- (NSData *)randomData
{
const int LENGTH = 100 * 1024 * 1024; // M
char *bytes = (char *)malloc(LENGTH * sizeof(char)); // Well that supposed to be static and dispatched_once, but I removed that when tried to fix leaks
for (NSInteger i = 0; i < LENGTH; ++i) {
bytes[i] = arc4random() % 256 - 128; // chosen by fair dice roll.
// guaranteed to be random.
}
NSData *data = [NSData dataWithBytes:(void *)bytes length:LENGTH];
free(bytes);
return data;
}
当我跑那个时,1分钟后1 GiB泄露并且仍然。结束系统的内存管理窗口和活动监视器,显示我使用的60 GiB交换。
我运行的仪器告诉我,Overall bytes
部分等于活动监视器显示的应用程序。但是,一次只有一个对象,分配图是锯,随机数据的指针在函数调用之间是恒定的。也许NSData
以某种方式持有源数组,但我根本无法解决这个难题。
答案 0 :(得分:6)
您可能希望围绕该循环的内容使用@autoreleasepool {},否则它将创建的临时对象将不会被清除。这可能是你问题的根源。