检测设备信息时可能发生内存泄漏

时间:2013-11-20 01:44:53

标签: ios objective-c memory-management memory-leaks

我在下面的代码中有内存泄漏,但实际上并不知道如何修复它。我试过制造机器=零;但那没用。有人有什么建议吗?提前谢谢。

size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
if ([platform isEqualToString:@"iPhone3,1"] || [platform isEqualToString:@"iPhone3,2"] || [platform isEqualToString:@"iPhone3,3"] || [platform isEqualToString:@"iPhone4,1"])
            [UINavigationBar appearance].barTintColor = [UIColor colorWithRed:255.0/255.0 green:220.0/255.0 blue:0.0/255.0 alpha:0.9];
machine = nil;

我在stringWithCSString:machine:potential leak of memory pointed to by 'machine'

中得到了泄漏

1 个答案:

答案 0 :(得分:4)

拨打malloc的电话需要与对free的通话配对。

machine = nil更改为free(machine)

BTW - 您的代码变得更容易:

#include <sys/utsname.h>

struct utsname si;
uname(&si);
if (strcmp(si.machine, "iPhone3,1") == 0 || strcmp(si.machine, "iPhone3,2") == 0 || strcmp(si.machine, "iPhone3,3") == 0 || strcmp(si.machine, "iPhone4,1") == 0) {
}

无需内存管理或创建NSString个对象。