2015-03-31 199 views
0

下面的代码位导致系统崩溃在我的C++应用程序:CFRelease导致崩溃

CFMutableDictionaryRef property_dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 

if (! property_dictionary) 
    break; 

CFDictionarySetValue(property_dictionary, CFSTR("somekey"), CFSTR("someval")); 
CFMutableDictionaryRef match_dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, 
        &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 

if (! match_dictionary) 
    break; 

CFDictionarySetValue(match_dictionary, CFSTR(kIOPropertyMatchKey), property_dictionary); 

io_iterator_t service = IOServiceGetMatchingService(kIOMasterPortDefault, match_dictionary); 

if (property_dictionary != NULL) 
    CFRelease(property_dictionary); 

// the following bit causes crash 
if (match_dictionary != NULL) 
    CFRelease(match_dictionary); 

不知IOServiceGetMatchingService有什么关系呢。

+0

是否崩溃消失,如果你删除通话到'IOServiceGetMatchingService'? – 2015-03-31 02:42:37

+0

是的,事实证明。 – Ash 2015-04-01 00:33:18

回答

1

IOServiceGetMatchingService()在存储器管理方面是特有的。它使用一个对传入字典的引用。由于您的代码只有一个引用,因此在调用后它不再拥有match_dictionary字典,并且不能在其上调用CFRelease()

docs:包含匹配信息,其中一个定值始终由该功能所消耗

matching一个CF字典...

+0

辉煌!肯,你是一个传奇人物。不知道为什么,但在阅读文档时,我完全错过了这一说法。 – Ash 2015-04-01 00:33:49

+0

@ken你可以看看我的下面的问题。 http://stackoverflow.com/questions/39873319/cfrelease-crash-in-ios10?noredirect=1#comment67038350_39873319 – CKT 2016-10-06 07:34:08