[英]Memory leak in c code
我使用一些非目標C代碼編寫了此方法,並且儀器告訴我有泄漏。 不僅如此,免費(char *)崩潰了...
任何幫助,將不勝感激。
謝謝
NSArray *keys = @[@"@\"NSMutableArray\""];
//Init result
id result = object;
//Iterate every key
for (id key in [dict allKeys]) {
//Convert key to const char
const char * c =(const char*)malloc(sizeof(uint32_t));
c = [key cStringUsingEncoding:NSASCIIStringEncoding];
//Use c to see if the class has this property
if (class_getProperty([object class], c)) {
//get the property
objc_property_t property = class_getProperty([result class], c);
//Get the property name and type
const char *name = (const char*)malloc(sizeof(uint32_t));
const char *type = (const char*)malloc(sizeof(uint32_t));
name = property_getName(property);
type =property_copyAttributeValue(property, "T");
//Cast const char to string
NSString *pNameString = [NSString stringWithFormat:@"%s",name];
NSString *typeString = [NSString stringWithFormat:@"%s",type];
//Add relationships
if ([keys containsObject:typeString]) {
//Get array of objects
NSArray *relationship = [dict objectForKey:pNameString];
NSMutableArray *allSubObjects = [[NSMutableArray alloc]init];
//Parse each individual object
for (NSDictionary *relationshipObj in relationship) {
//Create class from relationship
Class class = NSClassFromString(pNameString);
//Create object
id sub = [self makeObject:[[class alloc]init] fromDictionary:relationshipObj];
[allSubObjects addObject:sub];
}
[result setValue:allSubObjects forKey:pNameString];
}else{
//If so set the property for the key
[result setValue:[dict objectForKey:key] forKey:key];
}
free((char*)name);
free((char*)type);
free(property);
}else{
//NSLog(@"%@ did not respond to : %@", result, key);
}
free((void*)c);
}
//Return result
return result;
崩潰是因為您分配c
,然后用cStringUsingEncoding:
返回的值覆蓋指針,然后嘗試釋放cStringusingEncoding
返回的cStringusingEncoding
(您的代碼不擁有此內容)。 另外,原始指針也會泄漏。
從文檔為cStringUsingEncoding
:
確保返回的C字符串僅在釋放接收器或清空當前內存之前才有效,以先到者為准。 如果需要在這段時間之后存儲C字符串,則應該復制C字符串或使用getCString:maxLength:encoding:。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.