Hypothesis:
It's to accomodate the NULL
char: \0
.
Documentation:
In Apple documentation found here for NSMaximumStringLength
NSMaximumStringLength
DECLARED IN foundation/NSString.h
SYNOPSIS NSMaximumStringLength
DESCRIPTION NSMaximumStringLength is the greatest possible length for an NSString.
And an NSString is but an "array of Unicode characters" - Source
NSString is concretized into either __NSCFString
during runtime or __NSCFConstantString
during compile time- Source
Memory Investigation of NSString:
Code
NSString *s1 = @"test";
Breaking during runtime in LLDB:
Type:
expr [s1 fileSystemRepresentation]
Output:
$0 = 0x0b92bf70 "test" // Essential memory location and content.
To view memory type in LLDB:
memory read 0x0b92bf70
Output:
0x0b92bf70: 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00 test............
0x0b92bf80: 7c 38 d4 02 72 a2 1b 03 f2 e6 1b 03 71 c5 4a 00 |8..r.......q.J.
*Notice empty termination after the last char t
.
Testing Hypothesis of NULL
termination:
Added a char*
to previous code:
NSString *s1 = @"test";
char *p = (char*)[s1 cString];
Break into code with LLDB and type:
expr p[4] = '\1' // Removing NULL char.
Now if we print NSString with command:
expr s1
Output:
(NSString *) $0 = 0x002f1534 @"test
Avg Draw Time: %g"
Notice garbage after the 't', "Avg Draw Time: %g" (aka buffer over reading).
Conclusion
Through inference we can observe that there is 1 byte
in the NSMaximumStringLength definition that is left for the NULL char to determine the end of a string in memory.