MACollectionUtilities
MACollectionUtilities copied to clipboard
Using DICT Macro causes segmentation fault
The DICT macro is never able to create a dictionary because a segmentation fault occurs in the static inlined function "MADictionaryWithKeysAndObjects". The compound literal (array of objects) keysAndObjs' elements points to objects on the heap that are no longer valid when that function attempts to subscript the array.
After a bit of investigation I found that if I made the "MADictionaryWithKeysAndObjects" a normal function that is not inlined the keysAndObjs array pointed to valid objects and the macro worked. I ensured that the compiler didn't optimize the MADictionaryWithKeysAndObjects into an inlined function by stepping through the assembly and ensuring that it used "call" instead of "jmp".
Oddly, it appears that the elements of keysAndObjs are being prematurely deallocated when MADictionaryWithKeysAndObjects is inlined. However, what is stranger, is that my dictionary contained a set of string literals as key/values which would make me think that those objects couldn't be deallocated anyhow since they are global strings.
This was happening consistently on the iOS Simulator 4.2 with both GCC 4.2 and LLVM GCC 4.2.
Code Snippet:
DICT(@"A", @"B", @"C", @"D");
That is deeply mysterious. Have you tried it with Clang to see if that crashes? Does it crash if you use normal ObjC objects rather than string literals?
I too am baffled which is why I hesitated posting this issue. However, I have found a repeatable way of introducing this issue that makes more sense to me now. I restored the MADictionaryWithKeysAndObjects function to a static inlined function and removed it from my precompiled header (pch) and instead included it where I needed and I no longer received a segmentation fault. However, when I re-introduced MACollections.h in the precompile header I got the exact same issue.
The lesson being that one shouldn't include a header that has static inline functions into a precompiled header. It causes devious and weird things to arise. I briefly did a search and found this page that warns against importing those kind of header files.