Global/static std::string leads to crash

Originator:simon
Number:rdar://16430946 Date Originated:2014-03-26
Status:Fixed Resolved:No
Product:iOS SDK Product Version:5.1
Classification: Reproducible:
 
Summary:
I have a minimal test case that causes a crash on iOS 5.1 when compiled with the iOS SDK 7.1, LLVM 5.1, and libstdc++.

The crash does not happen with -O0 or -O1, but -Os and -O2 and above all trigger the crash. It is occurring somewhere in the std::string implementation.

The same build runs fine on iOS 6 and 7 devices.

Steps to Reproduce:
1. Open the attached project in XCode 5.1
2. Run it on an iOS 5.1 device
3. See it crash with a message similar to this:

CrashTest(1014) malloc: *** error for object 0x2fee4c80: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

Expected Results:
It should print out "base/path".

Actual Results:
There is a crash, XCode reports it as being in the line:
return directory + "/" + path;

Commenting out the comparison with the global string makes the code work as expected.

Version:
Tested on iOS 5.1 (9B176) on both iPhone 4 (MC603B) and iPod touch 4G (MC540BT)

Notes:
When built with XCode 5.0.2, iOS SDK 7.0 and LLVM 5.0 the crash does not happen.

I'd like to understand if the optimizer in LLVM 5.1 is producing invalid code or if it is simply optimizing something differently and triggering a bug in the version of libstdc++ shipped with iOS 5.1.

Our ways forward: Stick to XCode 5.0.2 for a bit, drop support for iOS 5, and/or switch to libc++. I'd like to get to the cause of this bug so we can make the right choice on that.

Configuration:
Occurs on iOS 5.1 device, when code is built with XCode 5.1, LLVM 5.1, and with C++ standard library set to libstdc++, and with optimisation set to -Os -O2 -O3.

Does not crash on later iOS releases.

Comments

Fixed in XCode 5.1.1

Apple released an update to XCode that fixes this crash. The release notes contained a mention of fixing crashes when targeting iOS 5.1. I'll put this down as a toolchain bug.

Here is the test code I attached:


#include <string>

std::string home_directory;

std::string BuildPath(const std::string directory, const std::string path)
{
  if(home_directory.compare(directory) == 0)
    printf("In home directory\n");

return directory + "/" + path;
}

int main(int, char* [])
{
  home_directory = "home";
  printf("Home: '%s'\n", home_directory.c_str());
  printf("BuildPath: '%s'\n", BuildPath("base", "path").c_str());
}

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!