CF释放导致崩溃

CFRelease causes crash

本文关键字:崩溃 释放 CF      更新时间:2023-10-16

以下代码导致我的C++应用程序崩溃:

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是否与此有关。

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

来自文档:

matching包含匹配信息的CF字典,其中一个引用总是被该函数使用…