CFRelease导致崩溃

时间:2015-03-31 02:20:59

标签: c++ macos

以下代码导致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是否与它有关。

1 个答案:

答案 0 :(得分:2)

IOServiceGetMatchingService()在内存管理方面很奇怪。它消耗对传入字典的一个引用。由于您的代码只有一个引用,因此在调用后它不再拥有match_dictionary字典,并且不得在其上调用CFRelease()

来自docs

  

matching 包含匹配信息的CF字典,其中一个引用始终由此函数使用...