1

I have a const string literal that is getting corrupted.

What is strange is that it is apparently behaving differently depending upon the version of XCode that is installed (I've got to do a few more experiments before I can 100% confirm this), but even if its not Xcode then I'm wondering what the cause could be.

If the exact same code is run on the exact same handset but with one run its connected to a laptop running Xcode 3.3.3 then this problem is manifesting, if the same code and same handset is run with a different laptop with XCode 4.3.2 or 4.4 installed then the problem does not manifest.

The issues is this:

HeaderFile.h
extern NSString* const kValue;

HeaderFile.m
NSString* const kValue = @"Some Value";

OtherFile.m
#import "HeaderFile.h"
...
NSLog(@"Value is: %@", kValue);

When connected to the laptop with Xcode 4.3.3 then the value logged or observed when debugging for the global constant is corrupt.

Any ideas how this could be?

As its a const literal it should not be possible for it to be scribbled over if there is a bug in my code.

UPDATE: I examined the value of kValue immediately after didFinishLaunchingWithOptions: gets called and its already corrupted at that point, so there's no opportunity for my code to scribble on it, even if it is scribable.

4

1 回答 1

1

由于它是一个 const 文字,如果我的代码中有错误,它不应该被乱写。

这并不完全正确。

首先, const 甚至可以通过简单的强制转换来移除。其次,如果您有一个严重的错误,您可能正在写入存储变量的内存,因为您正在访问另一个变量的内存之外(例如,如果您获取 a 的地址short并将其转换为类型long*然后访问它)。第三,您将指针本身声明为 const,但指向的数据不是 const(至少不是根据声明)。

另一方面,一般来说,你观察到的东西确实是不可能的。通常,声明为 const 的全局变量放在运行时只读的内存区域中。但并非所有硬件都允许这样做,并且对编译器没有真正的要求。通常,字符串文字也被视为 const,这意味着实际上您指向的内容也可能存储在 const 区域中(即使指针不是 const)。

我不知道你为什么会观察到这种行为,而且我不知道编译器和 iPhone 硬件的内部结构,所以我不能说是否真的不可能因为错误而修改该数据。但我知道根据语言规则,编译器(和硬件)将所有内容存储在可修改区域中是完全合法的。如果这就是他们所做的,那么是的,一个错误可能是问题所在。

于 2012-08-23T03:43:30.047 回答