Objective c 未释放类\u copyPropertyList上的内存泄漏
所以,我的应用程序有一些漏洞。一个是objc_property_t*properties=class_copyPropertyListself.class,NULL;没有自由 但当我添加freeproperties时 alloc:**对象0x10b773f58的错误:未分配要释放的指针 ***在malloc\u error\u break中设置断点以进行调试 代码如下所示:Objective c 未释放类\u copyPropertyList上的内存泄漏,objective-c,memory-leaks,runtime,Objective C,Memory Leaks,Runtime,所以,我的应用程序有一些漏洞。一个是objc_property_t*properties=class_copyPropertyListself.class,NULL;没有自由 但当我添加freeproperties时 alloc:**对象0x10b773f58的错误:未分配要释放的指针 ***在malloc\u error\u break中设置断点以进行调试 代码如下所示: - (void) encodeWithCoder:(NSCoder *)aCoder { objc_proper
- (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的指针数组,用于描述类声明的属性。不包括由超类声明的任何属性。数组包含*超出计数指针,后跟空终止符。必须用free释放数组
代码可以工作,但会泄漏。现在,当我添加freeproperties时,它会崩溃。您正在增加循环中的properties指针,因此在调用freeproperties时,它不再引用相同的内存地址。因此,被释放的指针未分配给消息
您需要以非破坏性的方式迭代属性,或者在循环之前将原始指针值复制到另一个指针变量
差不多
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);
您正在增加循环中的属性指针,因此在调用freeproperties时,它不再引用相同的内存地址。因此,被释放的指针未分配给消息
您需要以非破坏性的方式迭代属性,或者在循环之前将原始指针值复制到另一个指针变量
差不多
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);