1

While perusing through the NSString header file I saw the following.

#define NSMaximumStringLength (INT_MAX-1)

Why is the maximum string length one short of INT_MAX? Is this to accomodate for a null terminator (\0)? A related article can be found here.

Community
  • 1
  • 1
Brian Tracy
  • 6,801
  • 2
  • 33
  • 48

1 Answers1

2

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 __NSCFStringduring runtime or __NSCFConstantString during compile time- Source

  • __NSCFString : Probably akin to __NSCFConstantString (See memory investigation below).

  • __NSCFConstantString: uses a char array allocation ( const char *cStr ) - 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.

Community
  • 1
  • 1
namar0x0309
  • 2,239
  • 1
  • 15
  • 15
  • 1
    Thankyou for your continued research. +1 – Brian Tracy May 26 '14 at 04:14
  • `fileSystemRepresentation` does not return the "Essential memory location and content". It returns a "C-string in a format and encoding suitable for use with file-system calls". That has nothing to do with the internal storage used for the NSString. – Martin R May 26 '14 at 05:36
  • @MartinR: I use that address to remove the NULL char and it modifies the NSString which modifies 'internal storage'. – namar0x0309 May 26 '14 at 05:45
  • 1
    Excellent investigation. Accepted answer – Brian Tracy May 26 '14 at 15:54