因此,分析我的应用程序有些泄漏。一个是objc_property_t *properties = class_copyPropertyList(self.class, NULL);
没有自由' d。
但是当我添加free(properties)
alloc: *** error for object 0x10b773f58: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
代码看起来像这样:
- (void) encodeWithCoder:(NSCoder *)aCoder {
objc_property_t *properties = class_copyPropertyList(self.class, NULL);
while (*properties != '\0') {
NSString *pname = [NSString stringWithUTF8String:property_getName(*properties)];
const char * attrs = property_getAttributes(*properties);
// do something here and set the value to be encoded
}
properties ++;
}
free(properties);
}
objc_property_t类型的指针数组,描述类声明的属性。超类声明的任何属性都不包括在内。该数组包含* outCount指针,后跟一个NULL终止符。您必须使用free()释放数组。
代码有效,但泄漏。现在,当我添加free(properties)
时,它会崩溃。
答案 0 :(得分:5)
您正在循环中递增properties
指针,因此当您调用free(properties)
时,它不再引用相同的内存地址。因此pointer being freed was not allocated
消息。
您需要以非破坏性方式迭代属性,或者在循环之前将原始指针值复制到另一个指针变量。
像
这样的东西unsigned int count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (unsigned int i = 0; i < count; i++) {
objc_property_t property = properties[i];
// ...
}
free(properties);
或
objc_property_t *properties = class_copyPropertyList([self class], NULL);
objc_property_t *iterationPointer = properties;
while (*iterationPointer != NULL) {
// ...
iterationPointer++;
}
free(properties);