// String pointer address and actual memory address var STR: string; pstr: pstring; PC: pchar; begin {It is declared before STR is assigned a value, the pointer address (@ Str):} showmessage (inttostr (INTEGER (@ Str); {1244652; this is the STR pointer address in the stack} {but no real storage string memory is allocated yet} showmessage (inttostr (INTEGER (STR); {0; 0 is null} STR: = 'delphi '; {after a value is assigned ...} showmessage (inttostr (INTEGER (@ Str); {1244652; this is the STR pointer address in the stack} showmessage (inttostr (INTEGER (STR); {4580800; this is the actual address of STR In the heap} {Get the string through the pointer address, where pstr is the string pointer defined previously} pstr :=@ STR; showmessage (pstr ^ ); {Delphi} {obtain a string from the actual address, where PC is the character pointer defined earlier} PC: = pchar (INTEGER (STR); showmessage (PC ); {Delphi} end;
A string (ansistring or string, for example, "form1") is stored in the memory as follows:
The yellow area is the location where the real string is stored. The memory address of the previously mentioned string is the location where "F" in this example is located;
The four blue bytes store an integer value, indicating the length of the string;
The last Red byte stores an empty character (#0), indicating the end of the string. It is also used to be compatible with the end string of Windows NULL;
The four green bytes are also an integer value, indicating the number of times the string is referenced (that is, several string pointers point to it ).
Let's look at the example:
VaR STR, S1, S2: string; pint: pinteger; begin STR: = self. text; {give the Form title to it; now STR points to the memory location where the form title is located} S1: = STR; {assign a value to S1} S2: = STR; {assign a value to S2; now the Form title already has three references: Str, S1, and S2} {STR, S1, and S2 are definitely different; but now it points to the same location of memory, test:} showmessage (inttostr (INTEGER (STR); {15190384} showmessage (inttostr (INTEGER (S1 ))); {15190384} showmessage (inttostr (INTEGER (S2); {15190384} {four bytes offset to the left is the position of the string length. Read it (it must be 5 ):} pint: = pinteger (INTEGER (STR)-4); showmessage (inttostr (pint ^); {5} {8 bytes offset to the left is the string reference count, read it (it must be 3):} pint: = pinteger (INTEGER (STR)-8); showmessage (inttostr (pint ^); {3} end;
When the reference count of a string memory is 0, Delphi Automatically releases it. This is why the string does not need to be manually released.
During the test, I found that the reference count of all constants and non-global variables is always "-1 ".