A long
string variable occupies four bytes of memory which contain a pointer to a
dynamically allocated string. When a long string variable is empty (contains a
zero-length string), the string pointer is nil and no dynamic memory is
associated with the string variable. For a nonempty string value, the string
pointer points to a dynamically allocated block of memory that contains the
string value in addition to a 32-bit length indicator and a 32-bit reference count.
The table below shows the layout of a long-string memory block.
|
Offset |
Contents |
|
-8 |
32-bit reference-count |
|
-4 |
length in bytes |
|
0..Length - 1 |
character string |
Length |
NULL character |
The NULL
character at the end of a long string memory block is automatically maintained
by the compiler and the built-in string handling routines. This makes it
possible to typecast a long string directly to a null-terminated string.
For string constants and literals, the compiler generates a memory block with the same layout as a dynamically allocated string, but with a reference count of -1. When a long string variable is assigned a string constant, the string pointer is assigned the address of the memory block generated for the string constant. The built-in string handling routines know not to attempt to modify blocks that have a reference count of -1.
一个长串占用4个字节的内存用于存放动态分配的串的指针。当一个长串变量为空(串的长度是零)时,串指针为nil并且没有任何动态内存与串变量相关联。对于一个非空的串值,串指针指向一个动态分配的内存块,该内存块包含了串值、一个32位的长度指示器和一个32位的引用计数器。下表是长串内存块的布局:
|
偏移量 |
内容 |
|
-8 |
32位的引用计数器 |
|
-4 |
32位、以字节计算的长度指示器 |
|
0..Length - 1 |
字符串 |
|
Length |
NULL字符 |
NULL字符位于长串内存块的最后一个字节,它被编译器和内建的串处理例程自动维护。这一设计是为了将长串直接转换为空结束串。
对于串常量和串文本,编译器产生一个与上述动态分配串布局相同的内存块,但引用计数被置为 -1。当一个串变量被赋予一个串常量时,串指针被赋予串常量内存块的地址。内建的串处理例程知道不能试图修改引用计数为 -1的块。