Hello,
I am currently working on a project that involves periodically querying OSLog to forward system log entries to a backend. While the functionality generally operates as expected, I have encountered a memory leak in my application. Through testing, I have isolated the issue to the following simplified code example:
#import <Foundation/Foundation.h>
#import <OSLog/OSLog.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
while(1) {
NSError *error = nil;
OSLogStore *logStore = [OSLogStore storeWithScope:OSLogStoreSystem error:&error];
if (!logStore)
NSLog(@"Failed to create log store: %@", error);
sleep(1);
}
}
return 0;
}
When running this example, the application exhibits increasing memory usage, consuming an additional 100 to 200 KB per iteration, depending on whether the build is Debug or Release.
Given that Automatic Reference Counting is enabled, I anticipated that the resources utilized by logStore
would be automatically released at the end of each iteration. However, this does not appear to be the case.
Am I using the API wrong?
I would appreciate any insights or suggestions on how to resolve this issue.
Thank you.
Your @autoreleasepool
needs to be within the while
loop.
I have a post, Objective-C Memory Management for Swift Programmers, that explains this stuff. Ironically, you’re actually working in Objective-C, but I suspect you’ll still find it useful.
ps This isn’t a leak per se, because the memory is still known to the system. Rather, it’s something we call abandoned memory. So, for example, it won’t show up in the Leaks instrument.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"