2013-11-28 166 views
0

我用一些非客观的c代码编写了这种方法,仪器告诉我存在泄漏。不仅如此,但免费(char *)崩溃...c代码中的内存泄漏

任何帮助,将不胜感激。

感谢

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; 
+0

对我来说看起来不像C ... –

+0

我认为它的C++,非目标c的东西(const char *) –

+1

泄漏报告究竟在哪里?哪一行是崩溃?你需要给我们更多的信息。 – Sebastian

回答

4

它崩溃,因为你分配c,然后覆盖与任何cStringUsingEncoding:返回指针,然后尝试释放什么被cStringusingEncoding返回,你的代码不拥有。另外,原始指针也被泄露。

弗罗姆的docscStringUsingEncoding

返回的C字符串被保证是唯一有效,直到该接收器被释放时,或直到当前存储器被清空,以先到者为准。您应该复制C字符串或使用getCString:maxLength:encoding:如果需要在此时间之后存储C字符串。

+0

谢谢。我会看看这是否有效 –